【问题标题】:Python: parent class as variablePython:父类作为变量
【发布时间】:2018-02-22 14:36:58
【问题描述】:

假设您在某些模块 parents.py 中有两个具有相同接口的父类

class Mother:
    def __init__(self):
         print("mother")

class Father:
    def __init__(self):
         print("father")

而你想使用一个子类,它可以对两个类都进行操作,比如

import parents

class Child:
    def __init__(self,parent_choice):
        parents.parent_choice.__init__()

是否可以选择正确的父对象作为变量来创建这样的子对象?像

import child

son_of_your_mother = Child(Mother)

最好的方法是为每个父级设置单独的模块(.py 文件)(如我的示例中所示)。 欢迎任何其他方法解决这个问题,只要它使两个父类分开(离婚通常对孩子有好处)。

【问题讨论】:

  • parents.parent_choice.__init__() 行出现错误。请不要编写明显不起作用的代码。
  • 抱歉对我来说不是那么明显。通常我会做 super().__init__(**args)。怎么不等价?
  • 不是很明显???只需测试您的代码!
  • 问题出在son_of_your_mother = child(mother),mother应该是mother的一个实例,而不是你提到的那一行。而且我没有实例化它,因为目标是在执行此操作时实例化一个对象,但继承类属性。当然代码不会像我说的那样工作,否则我不会有任何疑问

标签: python class parent-child


【解决方案1】:

将母亲和父亲定义为子属性,将两者作为对母亲和父亲对象实例的引用(有关系)

class Mother:
    ...

class Father:
    ...

class Child:
    def __init__(self, mother, father):
        self.mother = mother
        self.father = father
        ...
    ...
    # use whatever attributes/methods you want from mother or father with
    # self.mother.somethod() or self.father.someattribute


mother1 = Mother() # create real objects from your classes
father1 = Father()
child1 = Child(mother1, father1) # pass them to the child `__init__`

Mother 和 Father 类的存放位置无关紧要。您可以将它们保存在同一个文件中或创建一个 family.py 模块,然后

from family import Mother, Father

class Child:
...

在当前脚本中定义您的孩子。

编辑:

根据您的 cmets,您需要从一些 Parent 类继承 Child 类,您还可以从该类继承 MotherFather 类。 这将继承方法和属性,但也会声明Child 也是Parent,而他不是。但它们都是Person,因此您可以创建一个具有公共属性和方法的Person 类,使用继承自Person 的Mother 和Father 类对其进行扩展,然后更改子类__init__ 以接收父母列表。你维持一个容器式的 has-a 关系,但现在一个孩子可以有很多父母。也许添加一个方法add_parent 将新父母附加到self.parents 的列表中。如果在Child 中创建方法只是为了委托(调用)父母中的相应方法变得费力,那么您可以考虑将Child 类也更改为从 Person 类继承,从而获得所有常见的父母机制。在这些场景中,您需要稍微修改一下代码,但我想您明白了。

【讨论】:

  • 谢谢,这部分解决了问题(如果不希望同时创建两个对象,可以添加条件语句)。我猜这个问题是结构性的而不是实际的,是 child 没有继承父母的类属性,而是包含它们。现在我将使用这个解决方案,但理想情况下我想调用,比如来自母亲的函数 foo as child.foo()。
  • 此外,通过这种解决方案,孩子可以参加的可能课程必须在孩子本身中进行硬编码,而能够添加额外的父母而不修改子班级会很有用
【解决方案2】:

我发现了一个非常相似的问题:Pass a parent class as an argument?

解决方案是定义一个包装类的函数。在这种情况下,就像

import parents

def Child(parent):

    class Child(parent):
         # stuff

    return Child

并创建实例

import child

c = Child(Mother)(**args)

【讨论】:

    【解决方案3】:

    您可以将字符串传递给Child,然后使用getattr 创建父对象。

    import parents
    
    class Child:
        def __init__(self,parent_choice):
            self.parent = getattr(parents, parent_choice)()
    

    那你就这样用吧

    son_of_your_mother = Child('Mother')
    

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多