我有下面的類不工作:的Python 2.7:爲什麼字符串格式雙__領域
class Members(object):
def __init__(self, variable=50):
self.__myvariable = variable
def getVariable(self):
return self.__myvariable
# attempt 1
def __repr__(self):
return """{self.__class__.__name__}({self.getVariable()})""".format(self=self)
# attempt 2
def __repr__(self):
return """{self.__class__.__name__}({self.__myvariable})""".format(self=self)
我不能找到一種方法,通過使用自如打印的格式字符串__變量一個關鍵,爲什麼是這樣?
我得到的錯誤是
AttributeError: 'Members' object has no attribute 'getVariable()'
AttributeError: 'Members' object has no attribute '__myvariable
所以string格式函數不明白方法的唯一屬性? – Har
通過閱讀格式[PEP-3101](https://www.python.org/dev/peps/pep-3101/),沒有關於提供對象的調用方法的一行。您可能能夠提供自己的格式化程序,請參閱自定義格式程序部分。 – chfw
查看我關於格式化字符串中調用方法的更新。 – chfw