简体   繁体   English

是否可以从子类中的超类方法访问变量?

[英]Is it possible to access the variable from a method of a superclass in a subclass?

I have a parent class "Parent" that has a method "method1". 我有一个父类“父”,它有一个方法“method1”。 This method uses a variable "b" that I want to access from the child class "Child". 此方法使用我想从子类“Child”访问的变量“b”。 When I tried to access it as self.b, python complained that "'Child' object has no attribute 'b'". 当我尝试将其作为self.b访问时,python抱怨“'Child'对象没有属性'b'”。 I am very new to object oriented programming and python. 我是面向对象编程和python的新手。 So maybe my understanding is incorrect. 所以也许我的理解是错误的。 Please help me explain why I am unable to access 'b'. 请帮我解释为什么我无法访问'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

I added the "self." 我加上了“自我”。 qualifier to variable "b" and added the same in the init function of the Parent class thinking that it will make it visible to the subclass. 变量“b”的限定符,并在Parent类的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

I was expecting that the output would be 我原以为输出会是

1
2

because I thought self.b under method1 will overwrite self.b in the init function. 因为我认为method1下的self.b会覆盖init函数中的self.b. However, the output is 但是,输出是

1
1

The problem is that you never call method1 anywhere, so the self.b never gets set to value 2 . 问题是你永远不会在任何地方调用method1 ,所以self.b永远不会被设置为值2

You could just remove the whole method1 and have the Parent class be like this: 你可以只删除整个method1 ,并有Parent类是这样的:

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

OR 要么

You could call the method1 in the Child class, for example: 您可以在Child类中调用method1 ,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM