我是python的新手,我不确定我在做什么是正确的.
我有一个基类A和一个继承的类B.
class A(object):
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self,name):
self.__name = name
class B(A):
def __init__(self,name):
super(NominalValue,self).__init__(name)
@property
def name2(self):
return self.__name2
@name2.setter
def name2(self,n):
self.__name2 = n
def toString():
print self.__name + self.__name2
if __name__ == "__main__":
instance = B('name');
instance.toString()
当我运行它时,它抱怨B类没有任何属性__name.
AttributeError: 'B' object has no attribute '_B__name'
最佳答案
以_ __name这两个下划线开头的属性被表示为私有变量.对这些没有实际的保护(也就是说:如果你能找到它,你可以访问它),但是它们被命名为不易访问. More information about that can be found on the docs page
原文链接:https://www.f2er.com/python/439422.htmlAny identifier of the form
__spam
(at least two leading underscores,at most one trailing underscore) is textually replaced with_classname__spam
,whereclassname
is the current class name with leading underscore(s) stripped.
因此,即使您继承了A的__name属性,在类型B的任何对象中也没有属性__name.您拥有的是_A__name属性.这就是名称修改的工作原理:__ attributename变为_classname__attributename