Python: Access base class “Class variable” in deri

2019-09-21 04:25发布

问题:

I am trying to access a class variable from the base class in the derived class and I am getting a no AttributeError

class Parent(object):
    variable = 'foo'

class Child(Parent):
    def do_something(self):
        local = self.variable

I tried using it as Parent.variable but that did not work either. I am getting the same error AttributeError: 'Child' object has no attribute 'Child variable'

How do i resolve this

回答1:

I'm not sure what you're doing wrong. The code below assumes you have an initialization method, however.

    class Parent(object):
        variable = 'foo'

    class Child(Parent):
        def __init__(self):
            pass
        def do_something(self):
            local = self.variable
            print(local)

    c = Child()
    c.do_something()

Output:

foo


回答2:

The code shown below should work on both Python 2 & 3:

class Parent(object):
    variable = 'foo'

class Child(Parent):
    def do_something(self):
        local = self.variable

c = Child()

print(c.variable)  # output "foo"


标签: python oop