Python: Inheritance versus Composition

前端 未结 2 2095
轮回少年
轮回少年 2020-12-01 11:26

I am working with two classes in Python, one of which should be allowed to have any number objects from another class as children while keeping an inventory of these childre

2条回答
  •  盖世英雄少女心
    2020-12-01 11:56

    First off, I think you are confusing things. As you yourself mention inheritance is used in a class that wants to inherit the nature of the parent class and then modify that behavior and extend it.

    In your example Child inherits two things from Parent. The constructor __init__ and havechild. You are overriding the constructor and the havechild method shouldn't work, since there is no kids member list to append the new child to. Also it appears that you are not intending to have the children have children.

    That being said it seems you may actually want to ask a different question, such as Composition vs Aggregation. There is such a design choice as Inheritance vs Composition which actually may be particularly interesting for Python, but it mainly asks whether you want to reuse code by copying the behavior of a standalone parent class (inheritance) or you want to separate different class behavior granules (for lack of better word) and then create classes which are compositions of these granules.

    have a look at this! The book referenced is also well known and has a good catalogue for different design patterns.

提交回复
热议问题