python - 无法在 Python 中访问父成员变量

标签 python inheritance scope

我正在尝试从扩展类访问父成员变量。但是运行以下代码...

class Mother(object):
    def __init__(self):
        self._haircolor = "Brown"

class Child(Mother):
    def __init__(self): 
        Mother.__init__(self)   
    def print_haircolor(self):
        print Mother._haircolor

c = Child()
c.print_haircolor()

告诉我这个错误:

AttributeError: type object 'Mother' has no attribute '_haircolor'

我做错了什么?

最佳答案

您混淆了类和实例属性。

print self._haircolor

关于python - 无法在 Python 中访问父成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064688/

相关文章:

python - 使用 python pandas 如何进行以下分析

python - 操作系统错误 : cannot open resource while trying to use ImageFont.

java - AP CS 实践 - OOP

java - 实例化通用抽象类的子(具体)类,其构造函数需要其他参数类

注入(inject)函数中的 Javascript 作用域

python - 使用 Python 和 AsyncIO 获取 JSON

python - 如何根据列值拆分数据框,对字符串值进行排序或分组?

c++ - 函数重载、继承和隐式构造函数 : weird priority

scope - 如何在 Gradle 构建中使用为 jar 文件提供的范围?

javascript - for循环的范围问题