简体   繁体   中英

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". This method uses a variable "b" that I want to access from the child class "Child". When I tried to access it as self.b, python complained that "'Child' object has no attribute 'b'". I am very new to object oriented programming and python. So maybe my understanding is incorrect. Please help me explain why I am unable to access '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.

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. 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 .

You could just remove the whole method1 and have the Parent class be like this:

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

OR

You could call the method1 in the Child class, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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