内置装饰器一:@classmethod、@staticmathod
生活随笔
收集整理的這篇文章主要介紹了
内置装饰器一:@classmethod、@staticmathod
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用 @classmethod 和 @staticmathod 后,類的方法的調(diào)用
- 一般來(lái)說(shuō),要使用某個(gè)類的方法,需要先實(shí)例化一個(gè)對(duì)象再調(diào)用方法。
- 而使用@staticmethod或@classmethod,就可以不需要實(shí)例化,直接類名.方法名()來(lái)調(diào)用。
這有利于組織代碼,把某些應(yīng)該屬于某個(gè)類的函數(shù)給放到那個(gè)類里去,同時(shí)有利于命名空間的整潔。
@staticmethod 和 @classmethod 都可以直接類名.方法名()來(lái)調(diào)用,他們的區(qū)別
- @staticmethod 不需要表示自身對(duì)象的 self 和自身類的 cls 參數(shù),就跟使用函數(shù)一樣。
- @classmethod 也不需要 self 參數(shù),但第一個(gè)參數(shù)需要是表示自身類的 cls 參數(shù)。
- 如果在 @staticmethod 中要調(diào)用到這個(gè)類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
- 而 @classmethod 因?yàn)槌钟?cls 參數(shù),可以來(lái)調(diào)用類的屬性,類的方法,實(shí)例化對(duì)象等,避免硬編碼。
總結(jié):
簡(jiǎn)單使用的時(shí)候使用@staticmethod, 需要調(diào)用類的其他屬性時(shí)使用@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/面向?qū)ο筮M(jìn)階.html
轉(zhuǎn)載于:https://www.cnblogs.com/ronky/p/9884155.html
總結(jié)
以上是生活随笔為你收集整理的内置装饰器一:@classmethod、@staticmathod的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 加装了固态硬盘怎么装系统 固态硬盘加装后
- 下一篇: Leetcode 295. 数据流的中位