Python中的對象,方法,類,實例,函數(shù)用法分析

字號:


    本文實例分析了Python中的對象,方法,類,實例,函數(shù)用法。分享給大家供大家參考。具體分析如下:
    Python是一個完全面向對象的語言。不僅實例是對象,類,函數(shù),方法也都是對象。
    復制代碼 代碼如下:class Foo(object):
    static_attr = True
    def method(self):
    pass
    foo = Foo()
    這段代碼實際上創(chuàng)造了兩個對象,F(xiàn)oo和foo。而Foo同時又是一個類,foo是這個類的實例。
    在C++里類型定義是在編譯時完成的,被儲存在靜態(tài)內(nèi)存里,不能輕易修改。在Python里類型本身是對象,和實例對象一樣儲存在堆中,對于解釋器來說類對象和實例對象沒有根本上的區(qū)別。
    在Python中每一個對象都有自己的命名空間??臻g內(nèi)的變量被存儲在對象的__dict__里。這樣,F(xiàn)oo類有一個__dict__, foo實例也有一個__dict__,但這是兩個不同的命名空間。
    所謂“定義一個類”,實際上就是先生成一個類對象,然后執(zhí)行一段代碼,但把執(zhí)行這段代碼時的本地命名空間設置成類的__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
    所謂“定義一個函數(shù)”,實際上也就是生成一個函數(shù)對象。而“定義一個方法”就是生成一
    個函數(shù)對象,并把這個對象放在一個類的__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. 直接調(diào)用類命名空間的函數(shù)和點
    運算返回的未綁定方法會得到不同的錯誤:
    復制代碼 代碼如下:>>> 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)
    但這兩個錯誤說的是一回事,實例方法需要一個實例。所謂“綁定方法”就是簡單地在調(diào)用方法時把一個實例對象作為第一個參數(shù)。下面這些調(diào)用方法是等價的:
    復制代碼 代碼如下:>>> Cheese.__dict__['get_weight'](stilton)
    '100g'
    >>> Cheese.get_weight(stilton)
    '100g'
    >>> Stilton.get_weight(stilton)
    '100g'
    >>> stilton.get_weight()
    '100g'
    最后一種也就是平常用的調(diào)用方式,stilton.get_weight(),是點運算符的另一種功能,將stilton.get_weight()翻譯成stilton.get_weight(stilton).
    這樣,方法調(diào)用實際上有兩個步驟。首先用屬性查找的規(guī)則找到get_weight, 然后將這個屬性作為函數(shù)調(diào)用,并把實例對象作為第一參數(shù)。這兩個步驟間沒有聯(lián)系。比如說你可以這樣試:
    復制代碼 代碼如下:>>> stilton.weight()
    Traceback (most recent call last):
    File "", line 1, in
    TypeError: 'str' object is not callable
    先查找weight這個屬性,然后將weight做為函數(shù)調(diào)用。但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是等價的。類對象和實例對象沒有本質區(qū)別,getattr(Cheese, 'smell')和Cheese.smell同樣是等價的。getattr()與點運算符相比,好處是屬性名用字符串指定,可以在運行時改變。
    __getattribute__()是最底層的代碼。如果你不重新定義這個方法,object.__getattribute__()和type.__getattribute__()就是getattr()的具體實現(xiàn),前者用于實例,后者用以類。換句話說,stilton.weight就是object.__getattribute__(stilton, 'weight'). 覆蓋這個方法是很容易出錯的。比如說點運算符會導致無限遞歸:
    復制代碼 代碼如下:def __getattribute__(self, name):
    return self.__dict__[name]
    __getattribute__()中還有其它的細節(jié),比如說descriptor protocol的實現(xiàn),如果重寫很容易搞錯。
    __getattr__()是在__dict__查找沒找到的情況下調(diào)用的方法。一般來說動態(tài)生成屬性要用這個,因為__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
    由于方法只不過是可以作為函數(shù)調(diào)用的屬性,__getattr__()也可以用來動態(tài)生成方法,但同樣要注意無限遞歸:
    復制代碼 代碼如下:>>> 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程序設計有所幫助。