是否能够从 Python 中的父对象创建子对象

Is it able to create a sub object from a parent object in Python

我想创建一个以另一个 class 对象作为父对象的对象。例如:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child()

class Child(Parent):
    def __init__(self):
        print(self.value)

obj = Parent()

假设输入是 3,我预期的打印输出也是 3。但是上面代码的实际输出是0。重点是,我想让sub class 继承Parent 的self 对象。不仅继承Parentclass的方法和class变量,还继承了一个实际调用并存在的Parentclass对象的实例变量。

我知道有一种方法可以做到这一点,如下所示:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self.value)

class Child(Parent):
    def __init__(self, value):
        self.value = value
        print(self.value)

obj = Parent()

但是如果有很多实例变量,这会很笨拙。此外,该值按值而不是引用传递给 Child。所以Child无法从Parent获取最新的实例变量值,但是我希望它能够实现。

另外,我知道还有一种方法如下:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self)

class Child(Parent):
    def __init__(self, parent):
        self.parent = parent
        print(self.parent.value)

obj = Parent()

但是这种方式似乎不是那么简洁。同时也会产生一些冗余资源,比如Parentclass的变量value = 0会被继承但是没有用(Childclass应该只对实例变量和方法感兴趣父 class 对象 obj)。我想知道有没有更好的方法可以达到我的目的

我知道应该有人问过类似的问题,但我不知道这个技术的名字是什么。因此,我找不到相关资料,决定问一下。

如果我理解正确,我认为你应该只实例化 Child class 而不是 Parent class.

将最后一行(从原始代码)更改为:

obj = Child()

根据您的评论,我认为您需要这样的东西:

class Parent:
    def __init__(self):
        self.value = int(input())

class Child:
    def __init__(self, parent):
        self._parent = parent

    def print_value(self)
        print(self._parent.value)

parent = Parent()  # input a number, for example 17

child1 = Child(parent)
child1.print_value()  # print 17
child2 = Child(parent)
child2.print_value()  # print 17

parent.value = 19
child1.print_value()  # print 19
child2.print_value()  # print 19

不清楚 call_subclass 会做什么。如果你想从 parent 的所有 children 中调用一些东西,那么

class Parent:
    def __init__(self):
        self.value = int(input())
        self._children = list()

    def register_child(self, child):
        self._children.append(child)

    def call_children_f(self, foo):
        for child in self._children:
            child.f(foo)

class Child:
    def __init__(self, parent, x):
        self._parent = parent
        self.x = x
        self._parent.register_child(self)

    def print_value(self)
        print(self._parent.value)

    def f(self, foo):
        print(f"Parent: {self._parent.value}, foo: {foo}, x: {self.x}")

parent = Parent()  # input a number, for example 17

child1 = Child(parent, 19)
child2 = Child(parent, 23)

parent.call_children_f(29)

这将打印:

Parent: 17, foo: 29, x: 19
Parent: 17, foo: 29, x: 23