1. 程式人生 > >python 中的內建函式 與 類

python 中的內建函式 與 類

python這種語言的變數命名規則有些奇葩,我相信大家已經遇到過了,比如:__future__。這種特殊的形式表明,這個

變數有特殊的意義,你不可以在自己的程式碼中創造這類變數。

1.__init__() 建構函式

類似於c++,java等面嚮物件語言,python 在類的定義中也有建構函式,這就是__init__()

__init__(parameters)中的變數parameter用來構建這個類的變數

例如:

class newclass(object):
"""docsng for newclass"""
    def __init__(self, aStr):
        self.aStr = aStr
	print "constructor is been used. "+self.aStr+" has been created"
hahaha = newclass("hello")

結果就是,constructor is been used. hello has been created

2.__del__() 解構函式

python 不需要進行記憶體管理,當一個類被扔到垃圾箱(garbage-collected)的時候,這個函式就會發揮功效。但是,你不會知道具體它什麼時候起作用,還是遠離它比較好。

3說說__init__()被過載(override)的情況

class Bird(object):
    def __init__(self):
        self.hungry = True
    def eat(self):
	if self.hungry:
	    print "Great"
	    self.hungry = False
	else:
	    print "No,thanks"


如果執行如下程式:
aBird = singBird()
aBird.eat()
程式會報錯,因為沒有了self.hungry這個變數

解決辦法為:

class singBird(Bird):
    def __init__(self):
	Bird.__init__(self)
	print "i am singing"



class singBird(Bird):
    def __init__(self):
	super(singBird,self).__init__()
	print "i am singing"


4.簡述python類中常用的內建函式

假設我們有一個字典 aDict = {'a': 1,‘b’:2}

__len__(self) 返回序列中收集item的個數 ,對於空的字典,列表,字串,元組,它們的邏輯值為False 

                      相當於len(aDict)

__getitem__(self,key) 返回與key相對應的值 。相當於aDict[key]

__setitem__(self.key,value) 將與key相對應的值設為value 。相當於aDict[key] = value

__delitem__(self,key) 將key與和key對應的item刪掉      del(aDict[key])

對於序列(元組,列表,字串)aList[-n] 相當於 aList[len(aList)-n]

5.靜態方法(staticmethod)和類方法(classmethod)

class myclass(object):
    def smeth():
        print "this is a static method"
    def cmeth(cls):
        print "this is a class method",cls
    cmeth = classmethod(cmeth)

這就是傳說中的裝飾器 
class myclass(object):
    @staticmethod
    def smeth():
        print "this is a static method"
    @classmethod
    def cmeth(cls):
        print "this is a class method",cls
當你使用@字元時,裝飾器(deractor)的使用就更加簡便。

呼叫myclass.smeth() 輸出 this is a static method

呼叫myclass.cmeth() 輸出 this is a class method <class '__main__.myclass'>

6.attribute 函式

__getattribute__(slef,name) 當使用名字為name的attribute時自動呼叫

__getattr__(self,name) 當使用名字為name的attribute時,實際上並不存在名字為name的attribute時,自動呼叫

__setattr__(self,name,value)賦值自動呼叫

__delattr__(self,name) 刪除自動呼叫

例如:

class Rectangle(object):
    def __init__(self):
        self.width = 0
        self.heigh = 0
    def __setattr__(self,name,value):
        if name  == 'width':
            self.width =value
        elif name == 'heigh':
            self.heigh = value
        else:
            raise AttributeError
    def __getattar__(self,name):
        if name == 'width':
            return self.width
        elif name == 'heigh':
            return self.heigh
        else:
            raise AttributeError

7. 迭代器Iterator

迭代器的功能非常強大,可以對任何物件進行迴圈

迭代的方式可以利用next()函式,或是for 迴圈

利用next()函式要注意:最後一個物件後,再進行next(),會產生StopIteration報錯

注意:在python 3.0中,next() 函式變為__next__()

class Fibb(object):
    def __init__(self):
        self.a = 0
        self.b = 1
    def next(self):
        self.a,self.b = self.b, self.a + self.b
        return self.a
    def __iter__(self):
        return self
fib = Fibb()
print next(fib)
print fib.next()

for i in fib:
    if i >800:
        print i 
        break

總而言之,含有__iter__()的類都是可迭代的,

含有next()的類才是迭代器。

所以對可迭代的類可以使用iter()函式

例如:

a =iter("anasiaj")
print a.next()
print a.next()
於是,有的人就會問,自己創造的迭代器,可不可以自己設定結束點呢?

當然可以,StopIteration 就相當於迴圈中的break

例子如下:

class aIter(object):
    def __init__(self):
        self.value = 0
    def next(self):
        self.value += 1
        if self.value > 15:
            raise StopIteration
        return self.value
    def __iter__(self):
        return self
aList = list(aIter())
print aList