我有下面的类不工作:的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