2016-09-06 83 views
0

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

回答

1

尝试1,因为format function完全不

尝试2调用方法失败,失败,因为名字改编BEHA的vior,看到PEP8

- __double_leading_underscore: when naming a class attribute, invokes name 
    mangling (inside class FooBar, __boo becomes _FooBar__boo; see below). 

通过阅读498,它发布了3.60a1,你可以做到这一点,你会得到 “成员(50)”:

class Members(object): 

    # attempt 3 
    def __repr__(self): 
     return f'{self.__class__.__name__}({self.getVariable()})' 
+0

所以string格式函数不明白方法的唯一属性? – Har

+1

通过阅读格式[PEP-3101](https://www.python.org/dev/peps/pep-3101/),没有关于提供对象的调用方法的一行。您可能能够提供自己的格式化程序,请参阅自定义格式程序部分。 – chfw

+0

查看我关于格式化字符串中调用方法的更新。 – chfw

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 
+0

这我不理解的点如果它确实受到损坏,那么getVariable()如何能够访问它? getVariable在外部作用域和字符串之间有什么区别? – Har

+1

函数'getVariable'是在'Members'类的上下文中创建的,所以python编译器可以在编译期间改变被访问的变量名。由于编译器不知道它需要检查字符串,所以对于字符串格式不能这样做。 – Dunes

0

你可以像这样,而不是将其格式化:

def __repr__(self): 
     return "{}({})".format(self.__class__.__name__,self.getVariable()) 

或像这样:

def __repr__(self): 
     return "{}({})".format(self.__class__.__name__,self.__myvariable)