定義類別屬性和方法
在類別中連結的任何變數都是 類別屬性。 任何在類別中定義的函數都是方法。 方法接收類別的實例(通常稱為 self
)作為第一個引數。 例如,若要定義部分類別屬性及方法,您可以輸入下列 Script:
class MyClass
attr1 = 10 #class attributes
attr2 = "hello"
def method1(self):
print MyClass.attr1 #reference the class attribute
def method2(self):
print MyClass.attr2 #reference the class attribute
def method3(self, text):
self.text = text #instance attribute
print text, self.text #print my argument and my attribute
method4 = method3 #make an alias for method3
在類別內,您應該使用類別名稱 (例如, MyClass.attr1
) 來限定類別屬性的所有參照。 對實例屬性的所有參照都應該使用 self
變數來限定 (例如, self.text
)。 在類別外部,您應該使用類別名稱 (例如, MyClass.attr1
) 或類別實例 (例如, x.attr1
,其中 x
是類別實例) 來限定類別屬性的所有參照。 在類別之外,對實例變數的所有參照都應該以類別的實例來限定 (例如, x.text
)。