python知识:@classmethod和@staticmethod的异同
生活随笔
收集整理的這篇文章主要介紹了
python知识:@classmethod和@staticmethod的异同
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 說明
????????@staticmethod的意思就是將后面的函數轉化成靜態函數。
????????大多數情況,@classmethod和@staticmethod效果一樣。但是那不是正題,正式作用是類工廠,如果有類繼承關系,更加明顯。
2??@staticmethod
就是將函數靜態化,如下例,將日期格式統一:
class Dates:def __init__(self, date):self.date = datedef getDate(self):return self.date@staticmethoddef toDashDate(date):return date.replace("/", "-")date = Dates("15-12-2016") dateFromDB = "15/12/2016" dateWithDash = Dates.toDashDate(dateFromDB)if(date.getDate() == dateWithDash):print("Equal") else:print("Unequal")date = Dates("15-12-2016")? ? ? ? 一種日期格式,(實例化后)
dateFromDB = "15/12/2016"? ? ? ?另一種日期格式
dateWithDash = Dates.toDashDate(dateFromDB)? ?無需實例化Dates得到日期格式
3?@classmethod的真實意義
2.1 類生成例
#!/usr/bin/python # -*- coding: UTF-8 -*-class A(object):bar = 1def func1(self): print ('foo') @classmethoddef func2(cls):print ('func2')print (cls.bar)cls().func1() # 調用 foo 方法A.func2() # 不需要實例化?2.1?@classmethod類工廠
from datetime import date# random Person class Person:def __init__(self, name, age):self.name = nameself.age = age@classmethoddef fromBirthYear(cls, name, birthYear):return cls(name, date.today().year - birthYear)def display(self):print(self.name + "'s age is: " + str(self.age))person = Person('Adam', 19) person.display()person1 = Person.fromBirthYear('John', 1985) person1.display()3? @classmethod和@staticmethod的區別
假設您創建了 Foo 的子類并在子類上調用了 create_new 方法
class Bar(Foo):passobj = Bar.create_new()然后這個基類將導致一個新的 Bar 對象被創建......
class Foo:@classmethoddef create_new(cls):return cls()而這個基類會導致創建一個新的 Foo 對象
class Foo:@staticmethoddef create_new():return Foo()采取哪一個?取決于你想要的行為。
總結
以上是生活随笔為你收集整理的python知识:@classmethod和@staticmethod的异同的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pyqt5知识:如何接受密码输入?
- 下一篇: QT5知识:装饰器@pyqtSlot和槽