无法访问父类的类属性

时间:2019-11-09 23:56:56

标签: inheritance attributes

我想访问父类中定义的变量,但我似乎无济于事。

class Parent():
    __variable = 2

class Child(Parent):

    def print_variable(self):
        print(__variable)

x = Child()
x.print_variable()

我收到错误消息...

  

NameError:名称'_Child__variable'未定义

我尝试了Parent.__variable,但收到错误消息...

  

AttributeError:类型对象“ Parent”没有属性   '_Child__variable'

编辑:这是因为我用'__'前缀命名变量。我以为我读过某个地方的惯例,就是用那个前缀来命名类属性。

0 个答案:

没有答案