我越過了一個有趣的問題。如何訪問課堂範圍內的「自我」?
假設我們有一個類,並且在它的構造函數中我們將一個布爾值作爲參數。我如何根據實例的條件/布爾值定義類中的方法?例如:
class X():
def __init__(self, x):
self.x = x
if self.x == true: # self is unreachable outside a method.
def trueMethod():
print "The true method was defined."
if self.x == false: # self is unreachable outside a method.
def falseMethod():
print "The false method was defined."
你爲什麼要這樣做?似乎它只會混淆用戶。 –
'self'就像其他語言的'this'。它只能用實例方法訪問。 – Nilesh
在構造函數中定義你的方法。如果你想讓他們成爲方法,給他們一個自我參數。 –