Python風格總結:Python基礎-類變量和實例變量

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:

通常來說,實例變量是對於每個實例都獨有的數據,而類變量是該類所有實例共享的屬性和方法。

其實我更願意用類屬性和實例屬性來稱呼它們,但是變量這個詞已經成爲程序語言的習慣稱謂。一個正常的示例是:

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中一切皆對象;類定義完成後,會在當前作用域中定義一個以類名爲名字,指向類對象的名字。如

class Dog:
	pass

會在當前作用域定義名字Dog,指向類對象Dog

類對象支持的操作
總的來說,類對象僅支持兩個操作:

  1. 實例化;使用instance_name = class_name()的方式實例化,實例化操作創建該類的實例。
  2. 屬性引用;使用class_name.attr_name的方式引用類屬性。

2.2 實例對象

實例對象是類對象實例化的產物,實例對象僅支持一個操作:

  1. 屬性引用;與類對象屬性引用的方式相同,使用instance_name.attr_name的方式。

按照嚴格的面向對象思想,所有屬性都應該是實例的,類屬性不應該存在。那麼在Python中,由於類屬性綁定就不應該存在,類定義中就只剩下函數定義了。

Python tutorial關於類定義也這麼說:

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.

實踐中,類定義中的語句通常是函數定義,但是其他語句也是允許的,有時也是有用的。

這裏說的其他語句,就是指類屬性的綁定語句。

3. 屬性綁定

在定義類時,通常我們說的定義屬性,其實是分爲兩個方面的:

  1. 類屬性綁定
  2. 實例屬性綁定

綁定這個詞更加確切;不管是類對象還是實例對象,屬性都是依託對象而存在的。

我們說的屬性綁定,首先需要一個可變對象,才能執行綁定操作,使用

objname.attr = attr_value

的方式,爲對象objname綁定屬性attr

這分兩種情況:

  1. 若屬性attr已經存在,綁定操作會將屬性名指向新的對象;
  2. 若不存在,則爲該對象添加新的屬性,後面就可以引用新增屬性。

3.1 類屬性綁定

Python作爲動態語言,類對象和實例對象都可以在運行時綁定任意屬性。因此,類屬性的綁定發生在兩個地方:

  1. 類定義時;
  2. 運行時任意階段。

下面這個例子說明了類屬性綁定發生的時期:

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的方式,這是一個特例,其實是等同於後面使用類名綁定屬性的方式。
因爲是動態語言,所以可以在運行時增加屬性,刪除屬性。

3.2 實例屬性綁定

與類屬性綁定相同,實例屬性綁定也發生在兩個地方:

  1. 類定義時;
  2. 運行時任意階段。

示例:

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類實例有兩個特殊之處:

  1. __init__在實例化時執行
  2. Python實例調用方法時,會將實例對象作爲第一個參數傳遞

因此,__init__方法中的self就是實例對象本身,這裏是dog,語句

self.name = name
self.age = age

以及後面的語句

dog.fur_color = 'red'

爲實例dog增加三個屬性nameagefur_color

4. 屬性引用

屬性的引用與直接訪問名字不同,不涉及到作用域。

4.1 類屬性引用

類屬性的引用,肯定是需要類對象的,屬性分爲兩種:

  1. 數據屬性
  2. 函數屬性

數據屬性引用很簡單,示例:

class Dog:

    kind = 'canine'

Dog.country = 'China'

print(Dog.kind, ' - ', Dog.country) # output: canine  -  China

通常很少有引用類函數屬性的需求,示例:

class Dog:

    kind = 'canine'

    def tell_kind():
    	print(Dog.kind)
    	
Dog.tell_kind() # Output: canine

函數tell_kind在引用kind需要使用Dog.kind而不是直接使用kind,涉及到作用域,這一點在我的另一篇文章中有介紹:Python進階 - 命名空間與作用域

4.2 實例屬性引用

使用實例對象引用屬性稍微複雜一些,因爲實例對象可引用類屬性以及實例屬性。但是實例對象引用屬性時遵循以下規則:

  1. 總是先到實例對象中查找屬性,再到類屬性中查找屬性;
  2. 屬性綁定語句總是爲實例對象創建新屬性,屬性存在時,更新屬性指向的對象。

4.2.1 數據屬性引用

示例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,按照規則,dog.country會引用到實例對象的屬性;但實例對象dog沒有屬性kind,按照規則會引用類對象的屬性。

示例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',按照規則,爲實例對象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 方法屬性引用

與數據成員不同,類函數屬性在實例對象中會變成方法屬性。

先看一個示例:

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'>

可以看到,類函數屬性在實例對象中變成了方法屬性,但是並不是實例對象中所有的函數都是方法。

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.

引用非數據屬性的實例屬性時,會搜索它對應的類。如果名字是一個有效的函數對象,Python會將實例對象連同函數對象打包到一個抽象的對象中並且依據這個對象創建方法對象:這就是被調用的方法對象。當使用參數列表調用方法對象時,會使用實例對象以及原有參數列表構建新的參數列表,並且使用新的參數列表調用函數對象。

那麼,實例對象只有在引用方法屬性時,纔會將自身作爲第一個參數傳遞;調用實例對象的普通函數,則不會。
所以可以使用如下方式直接調用方法與函數:

mt.inner_test()
mt.outer_test()

除了方法與函數的區別,其引用與數據屬性都是一樣的

5. 最佳實踐

雖然Python作爲動態語言,支持在運行時綁定屬性,但是從面向對象的角度來看,還是在定義類的時候將屬性確定下來。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章