classmethod和staticmethod
生活随笔
收集整理的這篇文章主要介紹了
classmethod和staticmethod
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
兩個裝飾器
classmethod : 被裝飾的方法會成為一個靜態方法
classmethod 什么時候用?
- 定義了一個方法,默認傳self,但是這個self沒有被用到
- 并且你在這個方法里用到了當前的類名,或者你準備使用這個類的內存空間中的名字的時候
定義:
裝飾器怎么加
參數怎么改
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
用法:
調用方法
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 # 類方法可以通過類名調用 Goodds.change_discount(0.6) apple = Goodds() print(apple.price) # 類方法可以通過對象名調用 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 : 被裝飾的方法會成為一個靜態方法
用在:
幫助我們把一個普通的函數挪到類中來直接使用,制造靜態方法用的
定義:
class User: # @staticmethod # def login(a, b): # print("登陸邏輯", a, b) # # 在函數的內部既不會用到self變量,也不會用到cls類 # 本身是一個普通的函數,被挪到類的內部執行,那么直接給這個函數添加@staticmethod裝飾器就可以了調用方法:
# class User: # @staticmethod # def login(a, b): # print("登陸邏輯", a, b) # # 在函數的內部既不會用到self變量,也不會用到cls類 # # obj = User() # User.login(1, 2) # obj.login(3, 4) class A:country = '中國'def func(self):print(self.__dict__)@classmethoddef clas_func(cls):print(cls)@staticmethoddef stat_func():print("普通函數")@propertydef name(self):return 'wahah'# 能定義到類中的內容 # 靜態變量 是個所有的對象共享的變量 有對象\類調用 但是不能重新賦值 # 綁定方法 是個自帶self參數的函數 由對象調用 # 類方法 是個自帶cls參數的函數 由對象\類調用 # 靜態方法 是個啥都不帶的普通函數 由對象\類調用 # property屬性 是個偽裝成屬性的方法 由對象調用 但不加括號
一些內置的魔術方法
- ___new___ class A:def __new__(cls, *args, **kwargs):o = object.__new__(cls)print("執行new", o)return odef __init__(self):print('執行initt', self)A() # 執行new <__main__.A object at 0x0000002F1E569048> # 執行initt <__main__.A object at 0x0000002F1E569048># 實例化的時候, # 先創建一塊對象的空間,有個指針能指向類 --》 __new__ # 調用init--> __init__# 設計模式 -- 單例模式 # 一個類,從頭到尾只會創建一次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('紅上衣', '綠褲子') # 通過模塊引用的方式 # 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) # 在打印一個對象的時候 調用__str__方法 # 在%s拼接一個對象的時候 調用__str__方法 # 在str一個對象的時候 調用__str__方法
- __repr__ py22 = clas() py22.append('大壯') print(py22) print(str(py22)) print('我們py22班 %s'%py22) print('我們py22班 %r'%py22) print(repr(py22)) # 當我們打印一個對象 用%s進行字符串拼接 或者str(對象)總是調用這個對象的__str__方法 # 如果找不到__str__,就調用__repr__方法 # __repr__不僅是__str__的替代品,還有自己的功能 # 用%r進行字符串拼接 或者用repr(對象)的時候總是調用這個對象的__repr__方法
轉載于:https://www.cnblogs.com/zh-lei/p/10995191.html
總結
以上是生活随笔為你收集整理的classmethod和staticmethod的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3 reqeusts后写入e
- 下一篇: redis配置主从复制