Python基礎(chǔ)-類變量和實例變量
寫在前面
如非特別說明检激,下文均基于Python3
大綱:
1. 類變量和實例變量
在Python Tutorial中對于類變量和實例變量是這樣描述的:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
通常來說蓖扑,實例變量是對于每個實例都獨有的數(shù)據(jù),而類變量是該類所有實例共享的屬性和方法。
其實我更愿意用類屬性和實例屬性來稱呼它們,但是變量這個詞已經(jīng)成為程序語言的習(xí)慣稱謂。一個正常的示例是:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
類Dog
中贝或,類屬性kind
為所有實例所共享;實例屬性name
為每個Dog
的實例獨有锐秦。
2. 類對象和實例對象
2.1 類對象
Python
中一切皆對象咪奖;類定義完成后,會在當(dāng)前作用域中定義一個以類名為名字酱床,指向類對象的名字羊赵。如
class Dog:
pass
會在當(dāng)前作用域定義名字Dog
,指向類對象Dog
扇谣。
類對象支持的操作:
總的來說昧捷,類對象僅支持兩個操作:
- 實例化;使用
instance_name = class_name()
的方式實例化罐寨,實例化操作創(chuàng)建該類的實例靡挥。 - 屬性引用;使用
class_name.attr_name
的方式引用類屬性衩茸。
2.2 實例對象
實例對象是類對象實例化的產(chǎn)物芹血,實例對象僅支持一個操作:
- 屬性引用;與類對象屬性引用的方式相同楞慈,使用
instance_name.attr_name
的方式幔烛。
按照嚴(yán)格的面向?qū)ο笏枷耄袑傩远紤?yīng)該是實例的囊蓝,類屬性不應(yīng)該存在饿悬。那么在Python
中,由于類屬性綁定就不應(yīng)該存在聚霜,類定義中就只剩下函數(shù)定義了狡恬。
在Python tutorial關(guān)于類定義也這么說:
In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.
實踐中,類定義中的語句通常是函數(shù)定義蝎宇,但是其他語句也是允許的弟劲,有時也是有用的。
這里說的其他語句姥芥,就是指類屬性的綁定語句兔乞。
3. 屬性綁定
在定義類時,通常我們說的定義屬性凉唐,其實是分為兩個方面的:
- 類屬性綁定
- 實例屬性綁定
用綁定這個詞更加確切庸追;不管是類對象還是實例對象,屬性都是依托對象而存在的台囱。
我們說的屬性綁定淡溯,首先需要一個可變對象,才能執(zhí)行綁定操作簿训,使用
objname.attr = attr_value
的方式咱娶,為對象objname
綁定屬性attr
。
這分兩種情況:
- 若屬性
attr
已經(jīng)存在强品,綁定操作會將屬性名指向新的對象豺总; - 若不存在,則為該對象添加新的屬性择懂,后面就可以引用新增屬性喻喳。
3.1 類屬性綁定
Python
作為動態(tài)語言,類對象和實例對象都可以在運(yùn)行時綁定任意屬性困曙。因此表伦,類屬性的綁定發(fā)生在兩個地方:
- 類定義時;
- 運(yùn)行時任意階段慷丽。
下面這個例子說明了類屬性綁定發(fā)生的時期:
class Dog:
kind = 'canine'
Dog.country = 'China'
print(Dog.kind, ' - ', Dog.country) # output: canine - China
del Dog.kind
print(Dog.kind, ' - ', Dog.country) # AttributeError: type object 'Dog' has no attribute 'kind'
在類定義中蹦哼,類屬性的綁定并沒有使用objname.attr = attr_value
的方式,這是一個特例要糊,其實是等同于后面使用類名綁定屬性的方式纲熏。
因為是動態(tài)語言,所以可以在運(yùn)行時增加屬性,刪除屬性局劲。
3.2 實例屬性綁定
與類屬性綁定相同勺拣,實例屬性綁定也發(fā)生在兩個地方:
- 類定義時;
- 運(yùn)行時任意階段鱼填。
示例:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog = Dog('Lily', 3)
dog.fur_color = 'red'
print('%s is %s years old, it has %s fur' % (dog.name, dog.age, dog.fur_color))
# Output: Lily is 3 years old, it has red fur
Python
類實例有兩個特殊之處:
-
__init__
在實例化時執(zhí)行 -
Python
實例調(diào)用方法時药有,會將實例對象作為第一個參數(shù)傳遞
因此,__init__
方法中的self
就是實例對象本身苹丸,這里是dog
愤惰,語句
self.name = name
self.age = age
以及后面的語句
dog.fur_color = 'red'
為實例dog
增加三個屬性name
, age
, fur_color
。
4. 屬性引用
屬性的引用與直接訪問名字不同赘理,不涉及到作用域宦言。
4.1 類屬性引用
類屬性的引用,肯定是需要類對象的商模,屬性分為兩種:
- 數(shù)據(jù)屬性
- 函數(shù)屬性
數(shù)據(jù)屬性引用很簡單蜡励,示例:
class Dog:
kind = 'canine'
Dog.country = 'China'
print(Dog.kind, ' - ', Dog.country) # output: canine - China
通常很少有引用類函數(shù)屬性的需求,示例:
class Dog:
kind = 'canine'
def tell_kind():
print(Dog.kind)
Dog.tell_kind() # Output: canine
函數(shù)tell_kind
在引用kind
需要使用Dog.kind
而不是直接使用kind
阻桅,涉及到作用域凉倚,這一點在我的另一篇文章中有介紹:Python進(jìn)階 - 命名空間與作用域
4.2 實例屬性引用
使用實例對象引用屬性稍微復(fù)雜一些,因為實例對象可引用類屬性以及實例屬性嫂沉。但是實例對象引用屬性時遵循以下規(guī)則:
- 總是先到實例對象中查找屬性稽寒,再到類屬性中查找屬性;
- 屬性綁定語句總是為實例對象創(chuàng)建新屬性趟章,屬性存在時杏糙,更新屬性指向的對象。
4.2.1 數(shù)據(jù)屬性引用
示例1:
class Dog:
kind = 'canine'
country = 'China'
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
dog = Dog('Lily', 3, 'Britain')
print(dog.name, dog.age, dog.kind, dog.country)
# output: Lily 3 canine Britain
類對象Dog
與實例對象dog
均有屬性country
蚓土,按照規(guī)則宏侍,dog.country
會引用到實例對象的屬性;但實例對象dog
沒有屬性kind
蜀漆,按照規(guī)則會引用類對象的屬性谅河。
示例2:
class Dog:
kind = 'canine'
country = 'China'
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
dog = Dog('Lily', 3, 'Britain')
print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 canine Britain
print(dog.__dict__) # {'name': 'Lily', 'age': 3, 'country': 'Britain'}
dog.kind = 'feline'
print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 feline Britain
print(dog.__dict__)
print(Dog.kind) # canine 沒有改變類屬性的指向
# {'name': 'Lily', 'age': 3, 'country': 'Britain', 'kind': 'feline'}
使用屬性綁定語句dog.kind = 'feline'
,按照規(guī)則确丢,為實例對象dog
增加了屬性kind
绷耍,后面使用dog.kind
引用到實例對象的屬性。
這里不要以為會改變類屬性Dog.kind
的指向鲜侥,實則是為實例對象新增屬性褂始,可以使用查看__dict__
的方式證明這一點。
示例3描函,可變類屬性引用:
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
print(d.tricks) # ['roll over', 'play dead']
語句self.tricks.append(trick)
并不是屬性綁定語句崎苗,因此還是在類屬性上修改可變對象狐粱。
4.2.2 方法屬性引用
與數(shù)據(jù)成員不同,類函數(shù)屬性在實例對象中會變成方法屬性胆数。
先看一個示例:
class MethodTest:
def inner_test(self):
print('in class')
def outer_test():
print('out of class')
mt = MethodTest()
mt.outer_test = outer_test
print(type(MethodTest.inner_test)) # <class 'function'>
print(type(mt.inner_test)) #<class 'method'>
print(type(mt.outer_test)) #<class 'function'>
可以看到肌蜻,類函數(shù)屬性在實例對象中變成了方法屬性,但是并不是實例對象中所有的函數(shù)都是方法幅慌。
Python tutorial中這樣介紹方法對象:
When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
引用非數(shù)據(jù)屬性的實例屬性時宋欺,會搜索它對應(yīng)的類轰豆。如果名字是一個有效的函數(shù)對象胰伍,Python會將實例對象連同函數(shù)對象打包到一個抽象的對象中并且依據(jù)這個對象創(chuàng)建方法對象:這就是被調(diào)用的方法對象。當(dāng)使用參數(shù)列表調(diào)用方法對象時酸休,會使用實例對象以及原有參數(shù)列表構(gòu)建新的參數(shù)列表骂租,并且使用新的參數(shù)列表調(diào)用函數(shù)對象。
那么斑司,實例對象只有在引用方法屬性時渗饮,才會將自身作為第一個參數(shù)傳遞;調(diào)用實例對象的普通函數(shù)宿刮,則不會互站。
所以可以使用如下方式直接調(diào)用方法與函數(shù):
mt.inner_test()
mt.outer_test()
除了方法與函數(shù)的區(qū)別,其引用與數(shù)據(jù)屬性都是一樣的
5. 最佳實踐
雖然Python
作為動態(tài)語言僵缺,支持在運(yùn)行時綁定屬性胡桃,但是從面向?qū)ο蟮慕嵌葋砜矗€是在定義類的時候?qū)傩源_定下來磕潮。