classmethod和staticmethod
生活随笔
收集整理的這篇文章主要介紹了
classmethod和staticmethod
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
兩個(gè)裝飾器
classmethod : 被裝飾的方法會(huì)成為一個(gè)靜態(tài)方法
classmethod 什么時(shí)候用?
- 定義了一個(gè)方法,默認(rèn)傳self,但是這個(gè)self沒(méi)有被用到
- 并且你在這個(gè)方法里用到了當(dāng)前的類名,或者你準(zhǔn)備使用這個(gè)類的內(nèi)存空間中的名字的時(shí)候
定義:
裝飾器怎么加
參數(shù)怎么改
class Goodds:__dicount = 0.8def __init__(self):self.__Price = 5self.price = self.__Price * self.__dicount@classmethoddef change_discount(cls, new_discount):cls.__dicount = new_discount
用法:
調(diào)用方法
class Goodds:__dicount = 0.8def __init__(self):self.__Price = 5self.price = self.__Price * self.__dicount@classmethoddef change_discount(cls, new_discount):cls.__dicount = new_discount # 類方法可以通過(guò)類名調(diào)用 Goodds.change_discount(0.6) apple = Goodds() print(apple.price) # 類方法可以通過(guò)對(duì)象名調(diào)用 apple.change_discount(0.5) apple2 = Goodds() print(apple2.price)# import time # class Date: # def __init__(self, year, month, day): # self.year = year # self.month = month # self.day = day # # @classmethod # def today(cls): # struct_t = time.localtime() # date = cls(struct_t.tm_year, struct_t.tm_mon, struct_t.tm_mday) # return date # # # date_obj = Date.today() # print(date_obj.year) # print(date_obj.month) # print(date_obj.day) # # 2019 # # 6 # # 5
staticmethod : 被裝飾的方法會(huì)成為一個(gè)靜態(tài)方法
用在:
幫助我們把一個(gè)普通的函數(shù)挪到類中來(lái)直接使用,制造靜態(tài)方法用的
定義:
class User: # @staticmethod # def login(a, b): # print("登陸邏輯", a, b) # # 在函數(shù)的內(nèi)部既不會(huì)用到self變量,也不會(huì)用到cls類 # 本身是一個(gè)普通的函數(shù),被挪到類的內(nèi)部執(zhí)行,那么直接給這個(gè)函數(shù)添加@staticmethod裝飾器就可以了調(diào)用方法:
# class User: # @staticmethod # def login(a, b): # print("登陸邏輯", a, b) # # 在函數(shù)的內(nèi)部既不會(huì)用到self變量,也不會(huì)用到cls類 # # obj = User() # User.login(1, 2) # obj.login(3, 4) class A:country = '中國(guó)'def func(self):print(self.__dict__)@classmethoddef clas_func(cls):print(cls)@staticmethoddef stat_func():print("普通函數(shù)")@propertydef name(self):return 'wahah'# 能定義到類中的內(nèi)容 # 靜態(tài)變量 是個(gè)所有的對(duì)象共享的變量 有對(duì)象\類調(diào)用 但是不能重新賦值 # 綁定方法 是個(gè)自帶self參數(shù)的函數(shù) 由對(duì)象調(diào)用 # 類方法 是個(gè)自帶cls參數(shù)的函數(shù) 由對(duì)象\類調(diào)用 # 靜態(tài)方法 是個(gè)啥都不帶的普通函數(shù) 由對(duì)象\類調(diào)用 # property屬性 是個(gè)偽裝成屬性的方法 由對(duì)象調(diào)用 但不加括號(hào)
一些內(nèi)置的魔術(shù)方法
- ___new___ class A:def __new__(cls, *args, **kwargs):o = object.__new__(cls)print("執(zhí)行new", o)return odef __init__(self):print('執(zhí)行initt', self)A() # 執(zhí)行new <__main__.A object at 0x0000002F1E569048> # 執(zhí)行initt <__main__.A object at 0x0000002F1E569048># 實(shí)例化的時(shí)候, # 先創(chuàng)建一塊對(duì)象的空間,有個(gè)指針能指向類 --》 __new__ # 調(diào)用init--> __init__# 設(shè)計(jì)模式 -- 單例模式 # 一個(gè)類,從頭到尾只會(huì)創(chuàng)建一次self的空間class Baby:__instance = Nonedef __new__(cls, *args, **kwargs):if cls.__instance is None:# cls.__instance = super().__new__(cls)cls.__instance = object.__new__(cls)return cls.__instancedef __init__(self, cloth, pants):self.cloth = clothself.pants = pantsb1 = Baby('紅毛衣', '綠褲子') print(b1.cloth) b2 = Baby('白襯衫', '黑褲子') print(b1.cloth) print(b2.cloth)# 單例模式2.0: class Baby:def __init__(self, cloth, pants):self.cloth = clothself.pants = pants b1 = Baby('紅上衣', '綠褲子') # 通過(guò)模塊引用的方式 # from 單例模式 import b1 # from 單例模式 import b1
- __cal__ """ Call self as a function. """ # class A: # pass # # obj = A() # print(callable(obj)) # Falseclass A:def __call__(self, *args, **kwargs):print('___', args) obj = A() print(callable(obj)) obj() # True # ___ ()
- __len__class Cls:def __init__(self, name):self.name = nameself.student = []def len(self):return len(self.student)def __len__(self):return len(self.student)py22 = Cls('py22') py22.student.append('abc') py22.student.append('123') py22.student.append('qaz') print(len(py22))class Pow:def __init__(self, n):self.n = ndef __pow2__(self):return self.n ** 2def pow2(obj):return obj.__pow2__()obj = Pow(10) print(pow2(obj))
- __str__ class Course: # def __init__(self, name, price, period): # self.name = name # self.price = price # self.period = period # # def __str__(self): # return self.name # # python = Course('python', 21800, '6 month') # linux = Course('linux', 19800, '5 month') # mysql = Course('mysql', 12800, '3 month') # go = Course('go', 15800, '4 month') # print(go) # # goclass cls:def __init__(self):self.student = []def append(self, name):self.student.append(name)def __str__(self):return str(self.student) py22= cls() py22.append('大壯') print("我們py22班 %s" %py22) print(py22) py22.append('小狀') print(py22) # 在打印一個(gè)對(duì)象的時(shí)候 調(diào)用__str__方法 # 在%s拼接一個(gè)對(duì)象的時(shí)候 調(diào)用__str__方法 # 在str一個(gè)對(duì)象的時(shí)候 調(diào)用__str__方法
- __repr__ py22 = clas() py22.append('大壯') print(py22) print(str(py22)) print('我們py22班 %s'%py22) print('我們py22班 %r'%py22) print(repr(py22)) # 當(dāng)我們打印一個(gè)對(duì)象 用%s進(jìn)行字符串拼接 或者str(對(duì)象)總是調(diào)用這個(gè)對(duì)象的__str__方法 # 如果找不到__str__,就調(diào)用__repr__方法 # __repr__不僅是__str__的替代品,還有自己的功能 # 用%r進(jìn)行字符串拼接 或者用repr(對(duì)象)的時(shí)候總是調(diào)用這個(gè)對(duì)象的__repr__方法
轉(zhuǎn)載于:https://www.cnblogs.com/zh-lei/p/10995191.html
總結(jié)
以上是生活随笔為你收集整理的classmethod和staticmethod的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python3 reqeusts后写入e
- 下一篇: redis配置主从复制