python靜態方法、類方法

來源:互聯網
上載者:User

標籤:dog   參數   注意   self   obj   name   int   def   assm   

常規:

1 class Dog(object):2     def __init__(self,name):3         self.name=name4 5     def eat(self):6         print(‘%s is eating‘%self.name)7 8 d1=Dog(‘lele‘)9 d1.eat()

1.靜態方法:名義上由類管理,而實際在調用時,需要手動把執行個體對象傳進去作參數

1 class Dog(object):2     def __init__(self,name):3         self.name=name4     @staticmethod5     def eat(self):6         print(‘%s is eating‘%self.name)7 8 d1=Dog(‘lele‘)9 d1.eat(d1)

2.類方法:只能訪問類變數,不能訪問執行個體變數

 1 class Dog(object): 2     name=‘xiaomei‘ 3     def __init__(self,name): 4         self.name=name 5  6     @classmethod 7     def eat(self): 8         print(‘%s is eating‘%self.name) 9 10 d1=Dog(‘lele‘)11 d1.eat()

執行個體變數name=‘lele‘,類變數name=‘xiaomei‘。

調用結果為:xiaomei is eating

3.屬性方法:把一個方法變為一個靜態屬性(用途:使用者只需要知道查詢結果(調用屬性),而複雜的實現過程不需要使用者知道。eg:第三方查詢航班)

 1 class Dog(object): 2     def __init__(self,name): 3         self.name=name 4  5   6     @property 7     def eat(self): 8         print(‘%s is eating‘%self.name) 9 10 d1=Dog(‘lele‘)11 d1.eat

lele is eating

若要增加參數,可以通過 @屬性方法名.setter  來實現

class Dog(object):    def __init__(self,name):        self.name=name        self.__food=None    #將一個方法變為靜態屬性    @property    def eat(self):        print(‘%s is eating %s‘ % (self.name,self.__food))    #更改屬性方法    @eat.setter    def eat(self,food):   #增加了參數        self.__food=food        print(‘%s is eating %s‘ % (self.name, self.__food))    #刪除屬性方法    @eat.deleter    def eat(self):        del self.__food        print(‘已刪除‘)d1=Dog(‘lele‘)d1.eatd1.eat=‘gutou‘   #變成靜態屬性後,注意賦值方式d1.eatdel d1.eat

lele is eating None
lele is eating gutou
lele is eating gutou
已刪除

 

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.