Python @staticmethod @classmethod


class jhy(object):
    """docstring for jhy"""
    def __init__(self, x):
        self.x = x

    def pf(self): 
        print(self.x)

    @classmethod 
    def class_pf(cls, x):
        print(x)

    @staticmethod
    def static_pf(x):
        print(x)

    @staticmethod
    def static_pf2():
        print('dont depedn on class or instance')
        



j = jhy('instance')
# 实例方法
# 传入实例,不能传入类
j.pf()
# jhy.pf() 将会报错

# 类方法(希望用类来调用)
# 传入cls,即参数为类,但是传入实例也运行
jhy.class_pf('class using class method')
j.class_pf('instance using class method')

# 静态方法,当做放在类中的普通def就好
# 传入 类 和 实例均可
# 1
j.static_pf('instance using static method')
jhy.static_pf('class using static method')

# 2
j.static_pf2()
jhy.static_pf2()

输出:

instance
class using class method
instance using class method
instance using static method
class using static method
dont depedn on class or instance
dont depedn on class or instance
[Finished in 0.2s]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容