03.5 类方法、静态方法、实例方法

代码

# 类方法、静态方法、实例方法

class Date:

    def __init__(self, year):
        self.year = year

    def tomorrow(self):
        """实例方法,针对实例调用"""
        self.year += 1

    @staticmethod
    def print_year():
        print("静态方法.@staticmethod, 若有调用需要使用类名.方法")
        return Date(2022)

    @classmethod
    def format_str(cls):
        """类方法"""
        print("类方法,@classmethod,若有调用需要使用类名.方法")

    def __str__(self):
        return f"year: {self.year}"


if __name__ == '__main__':
    date = Date(2020)
    date.tomorrow()
    print(date)
    Date.print_year()
    Date.format_str()
原文地址:https://www.cnblogs.com/zy7y/p/14193464.html