Python:访问基类“类变量"在派生类中 [英] Python: Access base class "Class variable" in derive class

查看:65
本文介绍了Python:访问基类“类变量"在派生类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从派生类中的基类访问一个类变量,但我得到一个没有 AttributeError

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

我尝试将其用作 Parent.variable 但这也不起作用.我收到同样的错误AttributeError: 'Child' 对象没有属性 'Child 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'

如何解决这个问题

推荐答案

下面显示的代码应该适用于 Python 2 &3:

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:访问基类“类变量"在派生类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆