2016-09-06 20 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)