python學習-----8.22--classmethod和staticmethod

來源:互聯網
上載者:User

標籤:pre   utf-8   就是   alt   time   arm   code   ini   複製   

一、Binder 方法

  1.綁定到類的方法:用classmethod裝飾器裝飾的方法。為類量身定製

    類.boud_method(),自動將類當作第一個參數傳入

    (其實對象也可調用,但仍將類當做第一個參數傳入)

    2.綁定到對象的方法:沒有任何裝飾器裝飾的方法。為對象量身定製

    對象.boud_method(),自動將對象當做第一個參數傳入

    (屬於類的函數。類可以調用,但必須按照函數的規則來,沒有自動傳值那麼一說)

HOST=‘127.0.0.1‘PORT=3306DB_PATH=r‘C:\Users\Administrator\PycharmProjects\test\物件導向編程\test1\db‘
View Code
import settingsclass MySQL:    def __init__(self,host,port):        self.host=host        self.port=port    @classmethod    def from_conf(cls):        print(cls)        return cls(settings.HOST,settings.PORT)print(MySQL.from_conf) #<bound method MySQL.from_conf of <class ‘__main__.MySQL‘>>conn=MySQL.from_conf()conn.from_conf() #對象也可以調用,但是預設傳的第一個參數仍然是類
View Code

 

二、非Binder 方法:用staticmethod裝飾器裝飾的方法

  1.不與類或對象綁定,類和對象都可以調用,但是沒有自動傳值那麼一說,就是一個普通工具而已

    注意:與綁定到對象方法區分開,在類中直接定義的函數,沒有被任何裝飾器裝飾的,都是綁定到對象的方法,可不是普通函數,對象調用該方法會自動傳值,,而staticmethod裝飾的方法,不管誰來採用,都沒有自動傳值一說

import hashlibimport timeclass MySQL:    def __init__(self,host,port):        self.id=self.create_id()        self.host=host        self.port=port    @staticmethod    def create_id(): #就是一個普通工具        m=hashlib.md5(str(time.time()).encode(‘utf-8‘))        return m.hexdigest()print(MySQL.create_id) #<function MySQL.create_id at 0x0000000001E6B9D8> #查看結果為普通函數conn=MySQL(‘127.0.0.1‘,3306)print(conn.create_id) #<function MySQL.create_id at 0x00000000026FB9D8> #查看結果為普通函數複製代碼
View Code

classmethod與staticmethod的區別

 

import settingsclass MySQL:    def __init__(self,host,port):        self.host=host        self.port=port    @staticmethod    def from_conf():        return MySQL(settings.HOST,settings.PORT)    # @classmethod #哪個類來調用,就將哪個類當做第一個參數傳入    # def from_conf(cls):    #     return cls(settings.HOST,settings.PORT)    def __str__(self):        return ‘就不告訴你‘class Mariadb(MySQL):    def __str__(self):        return ‘<%s:%s>‘ %(self.host,self.port)m=Mariadb.from_conf()print(m) #我們的意圖是想觸發Mariadb.__str__,但是結果觸發了MySQL.__str__的執行,列印就不告訴你:
View Code

 

python學習-----8.22--classmethod和staticmethod

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.