class Example:
def __init__(self, x):
self.x = x
def function(self, y=self.x):
pass
Example(72)
當我運行此代碼時,我收到以下錯誤。
Traceback (most recent call last):
File "/home/millertime/Desktop/example.py", line 1, in <module>
class Example:
File "/home/millertime/Desktop/example.py", line 7, in Example
def function(self, y=self.x):
NameError: name 'self' is not defined
顯然,Python 不喜歡將引數預設到類變數中。有沒有合適的方法來做到這一點?我知道類資訊是在第一個引數中傳遞的,self. 有什么方法可以進一步參考它以使我的代碼成為可能?我試過改成y=self.x,y=x但我懷疑這只是扔了一個NameError. 我很清楚在函式內部執行此操作的其他方法,但我對它是否可能感興趣。
uj5u.com熱心網友回復:
在python中,函式默認引數中的運算式是在定義函式時計算的,而不是在呼叫它時計算的。在上述情況下,不會有任何實體化,因此會出現錯誤。
你可以這樣做
class Example:
def __init__(self, x):
self.x = x
def function(self, y=None):
if y is None:
y=self.x
pass
Example(72)
uj5u.com熱心網友回復:
Python檔案說:
執行函式定義時,從左到右計算默認引數值。這意味著運算式在定義函式時被計算一次,并且每次呼叫都使用相同的“預計算”值。
當您設定默認引數值y = self.x時,它會在執行函式定義時進行評估,此時self未定義(實體)。
一個常見的補救措施(也在檔案中提出)是設定y = None為默認值,并用于if y is None檢查是否y給出了引數值。
class Example:
def __init__(self, x):
self.x = x
def function(self, y=None):
if y is None:
y = self.x
return y
ex = Example(72)
print(ex.function()) # 72
print(ex.function(42)) # 42
uj5u.com熱心網友回復:
這可行,盡管它不一定比在您提到的函式中執行此操作的其他方法更可口:
class Example:
def __init__(self, x):
self.x =x
def _function(self, y):
return y * self.x
def normal_func(self, y):
return y self.x
def __getattr__(self, attr):
if attr == 'function':
return lambda y=self.x: self._function(y)
return super().__getattr__(self, attr)
a = Example(5)
print(a.function(10)) # should return 10 * 5
print(a.function()) # should return 5 * 5
print(a.normal_func(7)) # should return 7 5
印刷:
50
25
12
請注意,如果您持有對函式物件的參考,然后稍后執行它,您可能不會得到預期的結果:
f = a.function # This instance of the function has default y=5
a.x = 8 # This doesn't change default y in our stored f
print(f()) # So this gives 5 * 8
印刷:
40
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498097.html
上一篇:Python類繼承動態類變數
