亚洲免费乱码视频,日韩 欧美 国产 动漫 一区,97在线观看免费视频播国产,中文字幕亚洲图片

      1. <legend id="ppnor"></legend>

      2. 
        
        <sup id="ppnor"><input id="ppnor"></input></sup>
        <s id="ppnor"></s>

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

        字號(hào):


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