python staticmethod,classmethod,普通函数的区别

本文深入探讨了Python中静态方法和类方法的区别与应用。通过具体示例解释了如何使用@staticmethod和@classmethod装饰器来定义这两种类型的方法,并展示了它们如何与实例方法交互,以及如何在类中修改和获取变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Test01:

    arg1 = 'xx'

    @staticmethod
    def static_fun_self(self):  # self只是变量
        print('static fun self:', self)

    @staticmethod
    def static_fun_cls(cls):   # cls只是变量
        print('static fun cls:', cls)

    @classmethod
    def set_cls_arg1(cls, arg1):
        cls.arg1 = arg1   # 设置类的值

    @classmethod
    def class_fun(cls):
        print('class fun' + cls.arg1)

    def fun(self):
        print('fun' + self.arg1)

    def set_arg1(self, arg1):
        self.arg1 = arg1  # 设置实例的值


if __name__ == '__main__':
    t1 = Test01()
    t1.set_arg1('ss')
    t1.set_cls_arg1('sx')
    t1.static_fun_cls('cls')
    t1.class_fun()
    t1.fun()

 

--------------------------

输出结果1.

t1 = Test01()
t1.set_arg1('ss')
t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()

----

static fun cls: cls
class funsx
funss

设置cls self的值不同获取的值也不一样

输出结果2.

t1 = Test01()
t1.set_arg1('ss')
# t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()

----

static fun cls: cls
class funxx
funss

设置self的值 cls获取不到

 

输出结果3.

t1 = Test01()
# t1.set_arg1('ss')
t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()

----

static fun cls: cls
class funsx
funsx

设置 cls的值 self, cls都可以获取到

输出结果4.

t1 = Test01()
# t1.set_arg1('ss')
# t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()

static fun cls: cls
class funxx
funxx

---------------------------

通过@staticmethod修饰的函数在类中获取不到self,cls, 相当于一个普通函数

通过@classmethod修饰的函数可以通过cls.变量名 改变类中变量的值其他函数的值也更改

instance函数可以通过self.变量名 改变调用者变量的值,其他函数的值不更改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值