日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

内置装饰器一:@classmethod、@staticmathod

發布時間:2025/5/22 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 内置装饰器一:@classmethod、@staticmathod 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用 @classmethod 和 @staticmathod 后,類的方法的調用

  • 一般來說,要使用某個類的方法,需要先實例化一個對象再調用方法。
  • 而使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調用。
    這有利于組織代碼,把某些應該屬于某個類的函數給放到那個類里去,同時有利于命名空間的整潔。

@staticmethod 和 @classmethod 都可以直接類名.方法名()來調用,他們的區別

  • @staticmethod 不需要表示自身對象的 self 和自身類的 cls 參數,就跟使用函數一樣。
  • @classmethod 也不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數。
  • 如果在 @staticmethod 中要調用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
  • 而 @classmethod 因為持有 cls 參數,可以來調用類的屬性,類的方法,實例化對象等,避免硬編碼。

總結:
簡單使用的時候使用@staticmethod, 需要調用類的其他屬性時使用@classmethod

示例

# -*- coding: utf-8 -*-class Washer:company = "Li"def __init__(self,water=10,scour=2):self._water = waterself.scour = scourself.year = 2010@staticmethoddef spins_ml(spins):# print("company:",Washer.company)# print('year:',self.year)return spins * 0.4@classmethoddef get_washer(cls,water,scour):print("company:",Washer.company)print('year:',self.year)return cls(water,cls.spins_ml(scour))@propertydef water(self):return self._water@water.setterdef water(self,water):if 0 < water <=500:self._water = waterelse:print("set Failure!")@propertydef total_year(self):return 2015 - self.yeardef set_water(self,water):self.water = waterdef set_scour(self,scour):self.scour = scourdef add_water(self):print('Add water:',self.water)def add_scour(self):print('Add scour:',self.scour)def start_wash(self):self.add_water()self.add_scour()print('Start wash...')

參考資料:http://blog.willdx.me/web/面向對象進階.html

轉載于:https://www.cnblogs.com/ronky/p/9884155.html

總結

以上是生活随笔為你收集整理的内置装饰器一:@classmethod、@staticmathod的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。