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
.
- I am aiming to avoid multiple inheritance, like
class CarrotGummy(Vegtable, Gummy)
, to not have the diamond problem, if both of them inheritFood
. - 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()
- Is assuming that we don't have
Gummy
objects that aren'tFruit
orVegtable
simplyfies the problems? For example - assuming we don't have aGummyBear
object.
版权声明:本文标题:class - Combining behaviors of two parent classes without using multiple inheritance in Python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738709039a2108084.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论