Python中的對象,方法,類,執行個體,函數用法分析_python

來源:互聯網
上載者:User

本文執行個體分析了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. 直接調用類命名空間的函數和點
運算返回的未Binder 方法會得到不同的錯誤:
複製代碼 代碼如下:
>>> 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)

但這兩個錯誤說的是一回事,執行個體方法需要一個執行個體。所謂“Binder 方法”就是簡單地在調用方法時把一個執行個體對象作為第一個參數。下面這些調用方法是等價的:
複製代碼 代碼如下:
>>> 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 callable

先尋找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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.