Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用方法定义的父类时出错_Python_Class_Oop_Inheritance_Instance - Fatal编程技术网

Python 使用方法定义的父类时出错

Python 使用方法定义的父类时出错,python,class,oop,inheritance,instance,Python,Class,Oop,Inheritance,Instance,我有以下课程: class A: def name(self): return self.__label class B(A): def __init__(self, name) self.__label = name ex1 = B('Tom') print ex1.name() 我得到的是: AttributeError: B instance has no attribute '_A__label' 有什么问题以及如何更正?在属性前面

我有以下课程:

class A:
    def name(self):
        return self.__label

class B(A):
    def __init__(self, name)
        self.__label = name

ex1 = B('Tom')
print ex1.name()
我得到的是:

AttributeError: B instance has no attribute '_A__label'

有什么问题以及如何更正?

在属性前面加上双下划线时,Python使用“”访问该属性。这意味着它将以以下格式在类上存储属性:
\uuuuuuu
。在您的示例中,
self.\u标签
将存储为
self.\u B\u标签
,因为您在B类方法中设置了它。但是,当您尝试在A类中使用该属性时,它会将
self.\uu label
转换为
self.\u A\uu label
,并发现未设置该属性


双下划线的使用情况是,即使子类派生了类,也要确保变量始终在类中。因为可能发生的情况是子类将变量重新定义为其他变量,因此使用双下划线变量会使这变得更加困难。

错误:使用了双下划线变量。如何修复:不要使用双下划线变量。为什么不允许使用双下划线变量?它对外界是隐藏的,但我使用的是在父类中定义的方法。为什么会出现问题?因为双下划线正好用于阻止父类或子类的访问(或覆盖)。它们几乎从来都不是你想要的;不要使用它们。那么我如何停止外部世界的访问(例如,用户的无意访问),但允许从父/子类访问?不要。只是:不要。Python的原则是“我们在这里都是同意的成年人”。无论如何,给你的属性加一个下划线,以清楚地表明除非你知道你在做什么,否则不应该访问它们,但是你不能阻止人们这样做,你也不应该尝试。