我有以下课程:
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)
我找不到使用 self 作为键在格式字符串中打印__变量的方法,为什么会这样?
我得到的错误是
AttributeError: 'Members' object has no attribute 'getVariable()'
AttributeError: 'Members' object has no attribute '__myvariable
答案 0 :(得分:3)
如果属性为private(以两个下划线__
开头),则其运行时的真实姓名为_ClassName__attribute
。因此,要获得__myvariable
,您应该要求_Members__myvariable
:
def __repr__(self):
return '{self.__class__.__name__}({self._Members__myvariable})'.format(self=self)
控制台中的示例:
>>> m = Members()
>>> m
Members(50)
>>> m._myvariable
50
>>> m.getVariable()
50
>>> m.__myvariable
AttributeError: 'Members' object has no attribute '__myvariable'
>>> m._Members__myvariable
50
答案 1 :(得分:1)
尝试1失败,因为format function根本没有调用方法
尝试2因名称损坏行为而失败,请参阅PEP8
- __double_leading_underscore: when naming a class attribute, invokes name
mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
通过阅读3.60a1发布的498,您可以执行此操作,您将获得“会员(50)”:
class Members(object):
# attempt 3
def __repr__(self):
return f'{self.__class__.__name__}({self.getVariable()})'
答案 2 :(得分:0)
您可以将其格式化为:
def __repr__(self):
return "{}({})".format(self.__class__.__name__,self.getVariable())
或者像这样:
def __repr__(self):
return "{}({})".format(self.__class__.__name__,self.__myvariable)
答案 3 :(得分:0)
您无法访问__myvariable
,因为有两个领先__的名称遭到破坏(请参阅Does Python have “private” variables in classes?)
并且python没有进行变量插值,因此其他方法也不起作用(参见python string format calling a function)
相反,你可以做
return """{0}({1})""".format(self.__class__.__name__, self.getVariable())