classmethod、staticclassmethod內建裝飾器函數

來源:互聯網
上載者:User

標籤:put   disco   ini   name   hang   eth   無法   self   概念   

# method 英文是方法的意思# classmethod   類方法    # 當一個類中的方法中只涉及操作類的靜態屬性時,此時在邏輯上,我們想要直接通過類名就可以調用這個方法去修改類的靜態屬性,此時可以用這個內建裝飾器函數# staticmethod  靜態方法# 類的方法 classmethodclass Goods:    discount = 0.5  # 折扣    def __init__(self, name, price):        self.name = name        self.__price = price    @property    def price(self):        return self.__price * Goods.discount    def change_discount(self, newdiscount):  # 修改折扣        Goods.discount = newdiscountapple = Goods(‘蘋果‘, 5)print(apple.price)  # 2.5apple.change_discount(2)    # 這麼操作可以修改折扣,但是概念上無法理解,因為折扣修改的是整個超市的折扣,但這裡居然用蘋果的方法修改了類的折扣,是不合理的print(Goods.discount)class Goods:    discount = 0.5  # 折扣    def __init__(self, name, price):        self.name = name        self.__price = price    @property    def price(self):        return self.__price * Goods.discount    @classmethod    # 被此裝飾器修飾的方法,也可以直接被類名調用了 cls代表類,像self(代表對象)    def change_discount(cls, newdiscount):  # 修改折扣        cls.discount = newdiscountapple = Goods(‘蘋果‘, 5)print(apple.price)Goods.change_discount(0.2)  # 此時就可以直接通過類名去調用方法,從而修改整個類的折扣了print(apple.price)  # 1.0# 類的靜態方法 staticmethod    # 在完全物件導向編程中,如果一個方法既和對象沒有關係,又和類沒有關係,那麼就用staticmethod將這個方法變成一個靜態方法class Login:    def __init__(self, name, password):        self.name = name        self.pwd = password    def login(self):        pass    @staticmethod   # 被裝飾的方法變為靜態方法,既和對象沒有關係,又和類沒有關係,n    def get_usr_pwd():        usr = input(‘使用者名稱‘)        pwd = input(‘密碼‘)        Login(usr, pwd)Login.get_usr_pwd() # 在完全物件導向編程中,如果一個方法既和對象沒有關係,又和類沒有關係,那麼就用staticmethod將這個方法變成一個靜態方法,可以直接這樣調用# 類方法和靜態方法,都是類調用的# 對象也是可以調用類方法和靜態方法的,但不應該這麼用

 

classmethod、staticclassmethod內建裝飾器函數

聯繫我們

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