python 类方法与静态方法

class Bird:
    #类方法
    @classmethod
    def fly(cls):
        print("类方法fly:",cls)
    #静态方法
    @staticmethod
    def info(p):
        print("静态方法 info:",p)

#类方法会自动绑定第一个参数,一般是类的名字
Bird.fly()

#静态方法不会自动绑定,因此程序必须手动绑定第一个参数
Bird.info("Bird")

print("-"*40)

b = Bird()
b.fly()

b.info(
"shun")

@classmethod 和 @staticmethod 其实就是装饰器,只不过这两个函数都是python内置的函数

posted @ 2021-12-12 11:04  朵朵奇fa  阅读(36)  评论(0编辑  收藏  举报