天天看點

python基礎程式設計:Python中的對象,方法,類,執行個體,函數用法分析

本文執行個體分析了Python中的對象,方法,類,執行個體,函數用法。分享給大家供大家參考。具體分析如下:

Python是一個完全面向對象的語言。不僅執行個體是對象,類,函數,方法也都是對象。

class Foo(object):
    static_attr = True
    def method(self):
        pass
foo = Foo()
           

這段代碼實際上創造了兩個對象,Foo和foo。而Foo同時又是一個類,foo是這個類的執行個體。

在C++裡類型定義是在編譯時完成的,被儲存在靜态記憶體裡,不能輕易修改。在Python裡類型本身是對象,和執行個體對象一樣儲存在堆中,對于解釋器來說類對象和執行個體對象沒有根本上的差別。

在Python中每一個對象都有自己的命名空間。空間内的變量被存儲在對象的__dict__裡。這樣,Foo類有一個__dict__, foo執行個體也有一個__dict__,但這是兩個不同的命名空間。

所謂“定義一個類”,實際上就是先生成一個類對象,然後執行一段代碼,但把執行這段代碼時的本地命名空間設定成類的__dict__. 是以你可以寫這樣的代碼:

>>> class Foo(object):
...     bar = 1 + 1
...     qux = bar + 1
...     print "bar: ", bar
...     print "qux: ", qux
...     print locals()
...
bar:  2
qux:  3
{'qux': 3, '__module__': '__main__', 'bar': 2}
>>> print Foo.bar, Foo.__dict__['bar']
2 2
>>> print Foo.qux, Foo.__dict__['qux']
3 3
           

所謂“定義一個函數”,實際上也就是生成一個函數對象。而“定義一個方法”就是生成一

個函數對象,并把這個對象放在一個類的__dict__中。下面兩種定義方法的形式是等價的:

>>> class Foo(object):
...     def bar(self):
...         return 2
...
>>> def qux(self):
...     return 3
...
>>> Foo.qux = qux
>>> print Foo.bar, Foo.__dict__['bar']
>>> print Foo.qux, Foo.__dict__['qux']

>>> foo = Foo()
>>> foo.bar()
2
>>> foo.qux()
3
           

而類繼承就是簡單地定義兩個類對象,各自有不同的__dict__:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> print Cheese.smell
good
>>> print Cheese.taste
good
>>> print Stilton.smell
bad
>>> print Stilton.taste
good
>>> print 'taste' in Cheese.__dict__
True
>>> print 'taste' in Stilton.__dict__
False
           

複雜的地方在

.

這個運算符上。對于類來說,Stilton.taste的意思是“在Stilton.dict__中找’taste’. 如果沒找到,到父類Cheese的__dict__裡去找,然後到父類的父類,等等。如果一直到object仍沒找到,那麼扔一個AttributeError.”

執行個體同樣有自己的__dict:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...     def get_weight(self):
...         return self.weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> stilton = Stilton('100g')
>>> print 'weight' in Cheese.__dict__
False
>>> print 'weight' in Stilton.__dict__
False
>>> print 'weight' in stilton.__dict__
True
           

不管__init__()是在哪兒定義的, stilton.__dict__與類的__dict__都無關。

Cheese.weight和Stilton.weight都會出錯,因為這兩個都碰不到執行個體的命名空間。而

stilton.weight的查找順序是stilton.dict => Stilton.dict =>

Cheese.dict => object.dict. 這與Stilton.taste的查找順序非常相似,僅僅是

在最前面多出了一步。

方法稍微複雜些。

>>> print Cheese.__dict__['get_weight']
>>> print Cheese.get_weight

>>> print stilton.get_weight
<__main__.Stilton object at 0x7ff820669190>>
           

我們可以看到點運算符把function變成了unbound method. 直接調用類命名空間的函數和點

運算傳回的未綁定方法會得到不同的錯誤:

>>> Cheese.__dict__['get_weight']()
Traceback (most recent call last):
  File "", line 1, in
TypeError: get_weight() takes exactly 1 argument (0 given)
>>> Cheese.get_weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: unbound method get_weight() must be called with Cheese instance as
first argument (got nothing instead)
           

但這兩個錯誤說的是一回事,執行個體方法需要一個執行個體。所謂“綁定方法”就是簡單地在調用方法時把一個執行個體對象作為第一個參數。下面這些調用方法是等價的

>>> Cheese.__dict__['get_weight'](stilton)
'100g'
>>> Cheese.get_weight(stilton)
'100g'
>>> Stilton.get_weight(stilton)
'100g'
>>> stilton.get_weight()
'100g'
           

最後一種也就是平常用的調用方式,stilton.get_weight(),是點運算符的另一種功能,将stilton.get_weight()翻譯成stilton.get_weight(stilton).

這樣,方法調用實際上有兩個步驟。首先用屬性查找的規則找到get_weight, 然後将這個屬性作為函數調用,并把執行個體對象作為第一參數。這兩個步驟間沒有聯系。比如說你可以這樣試:

>>> stilton.weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'str' object is not callabl
           

先查找weight這個屬性,然後将weight做為函數調用。但weight是字元串,是以出錯。要注意在這裡屬性查找是從執行個體開始的:

>>> stilton.get_weight = lambda : '200g'
>>> stilton.get_weight()
'200g'
           

但是

>>> Stilton.get_weight(stilton)
'100g'
           

Stilton.get_weight的查找跳過了執行個體對象stilton,是以查找到的是沒有被覆寫的,在Cheese中定義的方法。

getattr(stilton, ‘weight’)和stilton.weight是等價的。類對象和執行個體對象沒有本質差別,getattr(Cheese, ‘smell’)和Cheese.smell同樣是等價的。getattr()與點運算符相比,好處是屬性名用字元串指定,可以在運作時改變。

getattribute()是最底層的代碼。如果你不重新定義這個方法,object.getattribute()和type.getattribute()就是getattr()的具體實作,前者用于執行個體,後者用以類。換句話說,stilton.weight就是object.getattribute(stilton, ‘weight’). 覆寫這個方法是很容易出錯的。比如說點運算符會導緻無限遞歸:

def __getattribute__(self, name):
        return self.__dict__[name]
           

getattribute()中還有其它的細節,比如說descriptor protocol的實作,如果重寫很容易搞錯。

getattr()是在__dict__查找沒找到的情況下調用的方法。一般來說動态生成屬性要用這個,因為__getattr__()不會幹涉到其它地方定義的放到__dict__裡的屬性。

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         return 'Dynamically created attribute "%s"' % name
...
>>> stilton = Stilton()
>>> print stilton.taste
good
>>> print stilton.weight
Dynamically created attribute "weight"
>>> print 'weight' in stilton.__dict__
False
           

由于方法隻不過是可以作為函數調用的屬性,getattr()也可以用來動态生成方法,但同樣要注意無限遞歸:

>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         if name.startswith('get_'):
...             def func():
...                 return getattr(self, name[4:])
...             return func
...         else:
...             if hasattr(self, name):
...                 return getattr(self, name)
...             else:
...                 raise AttributeError(name)
...
>>> stilton = Stilton('100g')
>>> print stilton.weight
100g
>>> print stilton.get_weight
>>> print stilton.get_weight()
100g
>>> print stilton.age
Traceback (most recent call last):
  File "", line 1, in
  File "", line 12, in __getattr__
AttributeError: age
           

内容就以上怎麼多,最後給大家推薦一個口碑不錯的公衆号【程式員學府】,這裡有很多的老前輩學習技巧,學習心得,面試技巧,職場經曆等分享,更為大家精心準備了零基礎入門資料,實戰項目資料,每天都有程式員定時講解Python技術,分享一些學習的方法和需要留意的小細節

python基礎程式設計:Python中的對象,方法,類,執行個體,函數用法分析