从 child - python3 引用 Parent 个属性

Reference Parent attributes from child - python3

我有一个我认为非常简单的任务,但它变成了我质疑我所知道的关于 类 的一切(公平地说,一开始并没有太多)。

我有一个 parent class,我想在要在 child class 中执行的计算中使用该实例的属性,这是从 parent class 的 init 创建。但是,我似乎无法从 child class.

中引用它们

我从 child class 中找到了 init parent class 的一些建议,然而,那只是在我的案例中创建了一个无限循环。

class User(object):
   def __init__(self, a, b):
    self.a = a
    self.b = b
    self.child.append(Child(c=4))

class Child(User)
   def __init__(self, c):
    self.c = c + User.b
    print self.c

从代码和问题来看,我猜 Child 实际上只需要访问 User 的一些属性,在这个例子中 self.b

继承不是可行的方法。继承是指您想要重用很多属性和方法,并且 re-implement 其中一些。就像两个 class "car" 和 "truck" 都继承自 class "vehicles"

你用 "Parent-Child" 描述的更像是所有权。 class 用户拥有一些 Child(作为属性),并且您希望 Child 访问其所有者的数据。您需要做的是将所有者 (parent) 的引用传递给 child.

class User(object):
   def __init__(self, b):
    self.b = b
    self.child.append(Child(c=4,parent=self))

class Child(object)
   def __init__(self, c, parent):
    self.parent=parent
    self.c = c + self.parent.b
    print(self.c)

当然,在这个非常简单的示例中,最明显的编程方式是在 child 构造函数中传递 b,如下所示:

class User(object):
   def __init__(self, b):
    self.b = b
    self.child.append(Child(4,b))

class Child(object)
   def __init__(self, c, b):
    self.c = c + .b
    print(self.c)

但对于更复杂的任务,传递对 parent 的引用可能更好或必要。