admin管理员组

文章数量:1205732

I will present here a problem equivalent to the one I encountered, as an example. Suppose I have these classes, that have attributes and methods I want to use in the objects I create later:

class Fruit:
    """Has lots of attributes and methods."""

class Vegtable:
    """Has lots of attributes and methods."""

class Gummy:
    """Has lots of attributes and methods."""

Now, Onion "is a" Vegtable, Apple "is a" Fruit, but I need to be able to support, for example - BananaGummy and CarrotGummy. CarrotGummy "is a" Vegtable, but also "is a" Gummy. I need to be able to have the attributes and methods of both Vegtable and Gummy.

  1. I am aiming to avoid multiple inheritance, like class CarrotGummy(Vegtable, Gummy), to not have the diamond problem, if both of them inherit Food.
  2. I have read about composition. But - there are cases that I do need to override or have a different behaivior for specific objects. So if I am doing something like the following, I can't enjoy the benefits of OOP, and I can't decide on different behaiviors based on the object.
class CarrotGummy:
   def __init__(self):
       vegtable = Vegtable()
       gummy = Gummy()
  1. Is assuming that we don't have Gummy objects that aren't Fruit or Vegtable simplyfies the problems? For example - assuming we don't have a GummyBear object.

本文标签: classCombining behaviors of two parent classes without using multiple inheritance in PythonStack Overflow