【问题标题】:Is it possible to access the variable from a method of a superclass in a subclass?是否可以从子类中的超类方法访问变量?
【发布时间】:2019-09-20 23:54:17
【问题描述】:

我有一个父类“Parent”,它有一个方法“method1”。此方法使用我想从子类“Child”访问的变量“b”。当我尝试以 self.b 访问它时,python 抱怨说“'Child' 对象没有属性'b'”。我对面向对象编程和 python 非常陌生。所以也许我的理解是不正确的。请帮我解释为什么我无法访问“b”。

class Parent(object):
    def __init__(self):
        self.a = 1
    def method1(self):
        b = 2

class Child(Parent):
    def __init__(self):
        super(Child,self).__init__()
        self.vara = self.a
        self.varb = self.b

x = Child()
print x.vara
print x.varb

我添加了“自我”。限定符到变量“b”,并在父类的 init 函数中添加相同的内容,认为它将使其对子类可见。

class Parent(object):
    def __init__(self):
        self.a = 1
        self.b = 1
    def method1(self):
        self.b = 2

class Child(Parent):
    def __init__(self):
        super(Child,self).__init__()
        self.vara = self.a
        self.varb = self.b

x = Child()
print x.vara
print x.varb

我期望输出是

1
2

因为我以为method1下的self.b会覆盖init函数中的self.b。 但是,输出是

1
1

【问题讨论】:

  • 你从不打电话给method1,那为什么self.b会被设置为2
  • 您需要在 self.varb = self.b 行之前的某个时间点执行 method1(无论是在 Parent 的 init 还是 Child 的 init 中,都没有关系),因此 self.b 在完成这项任务的时间。

标签: python


【解决方案1】:

问题是您永远不会在任何地方调用method1,因此self.b 永远不会设置为值2

您可以删除整个 method1 并让 Parent 类如下所示:

class Parent(object):
    def __init__(self):
        self.a = 1
        self.b = 2

您可以在Child 类中调用method1,例如:

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.method1()
        self.vara = self.a
        self.varb = self.b

【讨论】:

  • 谢谢!我没有意识到我错过了对 method1 的调用。
  • @SaravanaChandramohan 没问题!如果您觉得它回答了您的问题,请随时 mark this as accepted :)
猜你喜欢
  • 2017-08-22
  • 2011-09-05
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多