python 方法、實例方法、靜態方法、類方法

十五、python 方法、實例方法、靜態方法、類方法

方法

1、實例方法

第一個參數是self,綁定到實例

2、類方法

@classmethod

第一個參數是cls,綁定到類

3、靜態方法

@staticmethod

和普通函數一樣,無綁定

4、特殊方法,如__init__()

 

 

-----------------------------------

#之前定義的好多方法都是實例方法

#剛纔寫的就是實例方法

def __init__(self,id,name,email):

self.Id = id

self.Name = name

self.Email = email

#靜態方法,

#靜態方法和類方法的應用場景。因爲python中是方法的多態,

但是怎麼做才能滿足多個不同參數的構造器呢?使用靜態方法

----------------------------------------------

#類描述符定義

class Property(object):

    def __init__(self, propname, datatype, default=None):

        self._name = '_'+propname+'_'

        self._type = datatype

        self._default = default if default else self._type()

 

    def __get__(self, instance, owner):

        return getattr(instance,self._name,self._default)

 

    def __set__(self, instance, value):

        if not isinstance(value,self._type):

            raise TypeError('Type Error,must be %s type0' % self._type)

        setattr(instance,self._name,value)

 

    def __del__(self):

        pass

 

class Email(Property):

    def __init__(self,propname,default=None):

        super(Email,self).__init__(propname,str,default)

 

    def __set__(self, instance, value):

        if not isinstance(value,self._type):

            raise TypeError('Type Error,must be %s type0' % self._type)

        if not '@' in value:

            raise ValueError('Email address is not valid')

        setattr(instance,self._name,value)

 

 

 

class Chinese(object):

    Id = Property('id', int) #描述符必須是類屬性,Id隨便定義,和後面沒有任何關係,它相當於對外訪問提供的一個接口

    Name = Property('name', str)

    Email = Email('email')

 

    #注意:類的成員方法中,也必須使用類的描述符

    def __init__(self,id,name,email):

        self.Id = id

        self.Name = name

        self.Email = email

#######################方法相關代碼###########################################

#想加一個這樣的多態構造器是不可行的

#    def __init__(self,id):

#        self.Id = id

#man = Chinese(10,'aidon','[email protected]')

 

    #定義一個靜態方法

    @staticmethod

    def getPeopleByParent(mather,father):

        print mather,father

        return Chinese(100,'aidon','[email protected]')  #相當於構造函數,最終創建咯實例對象

 

    @classmethod

    def getPeopleBySibling(cls,sibling):

        print sibling

        return cls(10,'bajie','[email protected]')

 

aidon = Chinese.getPeopleByParent('mm','dd')  #掉用靜態方法需要使用類

bajie = Chinese.getPeopleBySibling('aidon') #掉用類方法需要使用類,但他們的區別就是它可以得到cls類和繼承後的不同

#交互式測試即可

aidon.Name

bajie.Name

 

#定義一個北京人的類繼承中國人

class beijing(Chinese):

    pass

bjaidon = beijing.getPeopleByParent('bj','ch')  #掉用靜態方法需要使用類

bjbajie = beijing.getPeopleBySibling('bjbajie') #掉用類方法需要使用類,但他們的區別就是它可以得到cls類和繼承後的不同

#交互式測試(體現兩者方法的不同)

type(bjaidon) #<class '__main__.Chinese'>  靜態方法沒有cls,所以沒有類的特性,它的類就是父類的信息

type(bjbajie) #<class '__main__.beijing'>  它有cls,所以它還有類的特性,有類的信息

---------------------------------------------------------------

發佈了49 篇原創文章 · 獲贊 60 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章