python中@staticmethod/@classmethod

python 中@staticmethod and @classmethod

  1. 对于类中的三种method的区别
    在这里插入图片描述
    a) 类中的正常方法,其中参数包含显示的self 参数–这个函数可以调用使用类的各个属性
    b) 通过@staticmethod声明的,属于类的静态方法–调用方法:instance.static_func()/CLASS.static_func()
    @staticmethod
    static_func(*arg)
    c)通过@classmethod声明的,属于类的类方法,
    @classmethod
    class_func(cls,*arg)–cls是类,调用:instance.class_func(*arg)/CLASS.class_func(*arg)

  2. 对于类中的普通函数,当需要调用的时候必须实例化,对于声明为staticmethod/classmethod ,不需要实例化,直接使用类名调用。

class Method:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def get_name(self):
        return (self.name)
    @staticmethod
    def static_func(lastname):
        print('called static func--{}'.format(lastname))
    @classmethod
    def class_func(cls,num=0):
        print('called class func--{}-->{}'.format(cls,num))
class Method_i(Method):
    pass
m = Method('bob',20)
n = Method_i('Su',30)
print(m.__dict__)
print(n.__dict__)

m.get_name()
m.static_func('Smith')
Method.static_func('Smith')
m.class_func(80)
Method.class_func(90)
print("*"*10)
n.get_name()
n.static_func('Sue')
Method_i.static_func('Sue')
n.class_func(100)

output:
{‘name’: ‘bob’, ‘age’: 20}
{‘name’: ‘Su’, ‘age’: 30}
called static func–Smith
called static func–Smith
called class func–<class ‘main.Method’>–>80
called class func–<class ‘main.Method’>–>90


called static func–Sue
called static func–Sue
called class func–<class ‘main.Method_i’>–>100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值