下面的代碼生成錯誤:Python的父類兒童私有變量的訪問
class A(object):
def say_something(self):
print (self.foo)
print(self.__bar)
class B(A):
def __init__(self):
self.foo='hello'
self.__something='world'
test=B()
test.say_something()
印刷的「你好」是成功的,但「世界」生成以下錯誤:
print(self.__bar)
AttributeError: 'B' object has no attribute '_A__bar'
我對此我感到驚訝,我希望我的父類有一個方法,可以訪問其子級保證的私有屬性。有沒有解決這個問題的標準方法?
附加問題:所以,如果我爲一個屬性使用單個下劃線,從不同的對象中使用它會不會是錯誤的?是一個單獨的下劃線說「我會使用這個,但你的用戶不應該」,或者甚至應該讓開發者把它看作是私有的。請問這段代碼是不好的風格:
class A(object):
def __init__(self):
self._foo='bar'
Class B(object):
def __init__(self):
a=A()
b=A._foo
您可能會發現以下問題很有用:[Python中對象名稱之前的單下劃線和雙下劃線的含義](http://stackoverflow.com/questions/1301346/the-meaning-of-a -single-and-a-double-underscore-before-an-object-name-in-python) –