Python:访问派生类中的基类“类变量”

2024-10-03 21:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从派生类中的基类访问一个类变量,得到一个noAttributeError

class Parent(object):
    variable = 'foo'

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

我试着用它作为Parent.variable,但也没用。我也犯了同样的错误 AttributeError: 'Child' object has no attribute 'Child variable'

我如何解决这个问题


Tags: selfchildobjectfoolocaldef错误基类
2条回答

我不知道你做错了什么。但是,下面的代码假设您有一个初始化方法。在

    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()

输出:

^{pr2}$

下面显示的代码应该同时适用于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"

相关问题 更多 >