Python: Access base class “Class variable” in deri

2019-09-21 03:59发布

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

标签: python oop
2条回答
时光不老,我们不散
2楼-- · 2019-09-21 04:18

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"
查看更多
孤傲高冷的网名
3楼-- · 2019-09-21 04:35

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
查看更多
登录 后发表回答