實例/成員變量是與一個類的特定實例相關聯的值,對於每個類可以是不同的,並且可以通過類方法訪問。例如,採取以下類文件:
class MyClass(object):
class_variable = "!"
def __init__(self, first_word, second_word):
self.__instance_variable_one = first_word
self.__instance_variable_two = second_word
def to_string(self):
return self.__instance_variable_one + " " + self.__instance_variable_two
請注意,這裏的實例變量帶有__前綴,表示這些應該是私有的。現在使用這個類:
object_instance_one = MyClass("Hello", "World")
object_instance_one.to_string()
Hello World
print object_instance_one.class_variable
!
注意,這是直接訪問的類變量,而不是通過一個方法。
print object_instance_one.to_string() + object_instance_one.class_variable
Hello World!
您可以覆蓋類變量,如果你想:
object_instance_one.class_variable = "!!!"
print object_instance_one.to_string() + object_instance_one.class_variable
Hello World!!!
現在因爲實例變量使用__聲明爲private,你通常不會直接而是修改這些使用屬性來提供允許您修改這些的方法。這些正確的方法允許您添加setter和getter方法(例如驗證或類型檢查)。一個例子:
class MyClass(object):
class_variable = "!"
def __init__(self, first_word=None, second_word=None):
self.__instance_variable_one = first_word
self.__instance_variable_two = second_word
@property
def instance_variable_one(self):
return self.__instance_variable_one
@instance_variable_one.setter
def instance_variable_one(self, value):
if isinstance(value, str):
self.__instance_variable_one = value
else:
raise TypeError("instance variable one must be of type str")
@property
def instance_variable_two(self):
return self.__instance_variable_two
@instance_variable_two.setter
def instance_variable_two(self, value):
if isinstance(value, str):
self.__instance_variable_two = value
else:
raise TypeError("instance variable two must be of type str")
def to_string(self):
return str(self.__instance_variable_one) + " " + str(self.__instance_variable_two)
用法:
object_instance_one = MyClass()
object_instance_one.instance_variable_one = "Hello"
object_instance_one.instance_variable_two = "World"
print object_instance_one.to_string() + object_instance_one.class_variable
Hello World!
object_instance_one.instance_variable_two = 2
File "C:/MyClass.py", line 38, in
object_instance_one.instance_variable_two = 2 File "C:/MyClass.py", line 28, in > >instance_variable_two raise TypeError("instance variable two must be of type str") TypeError: instance variable two must be of type str
實例屬性是指一類的特定實例,其中可以有許多的屬性。類屬性是指類本身的屬性,它們由實例繼承,但在類中定義(除非在實例中被重寫)。 –