Python的classmethod和staticmethod

class DateTest:
    def __init__(self, year, month, day):
        self.day = day
        self.month = month
        self.year = year

    @ classmethod
    def turnDate(cls, datestr):
        year, month, day = map(int, datestr.split('-'))
        return cls(year, month, day)

    @ staticmethod
    def printStatic():
        print("--我是个静态方法--")

    def printDate(self):
        print(f"年:{self.year}, 月:{self.month},日:{self.day}")


# 原来的调用方式
dt = DateTest(2022, 5, 10)
dt.printDate()

# 但是如果新的需求时传入类似2022-05-10这种形式,就可以利用@classmethod类方法,调用方式如下
dt2 = DateTest.turnDate('2022-9-18')
dt2.printDate()


# staticmethod调用,不用实例化对象
DateTest.printStatic()
posted @ 2022-05-10 16:02  浅浅水声  阅读(20)  评论(0编辑  收藏  举报