python中的classmethod与staticmethod

classmethod、staticmethod是分别指定函数为动态方法还是静态方法,先看下面这个例子:

class Person:

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

    @classmethod
    def work(cls, name):
        return "%s is working!!!" % name

    @staticmethod
    def eat(name):
        return "%s is eating!!!" % name

    def sleep(self):
        return "%s is eating!!!" % self.name

print(Person.work)
print(Person.eat)
print(Person.sleep)

打印结果为:

<bound method Person.work of <class '__main__.Person'>>
<function Person.eat at 0x00000000025DAA60>
<function Person.sleep at 0x00000000025DAAE8>

可以看到@classmethod的函数是绑定的method而不是function,那么method和function有什么区别呢,先看下说明:

function —— A series of statements which returns some value toa caller. It can also be passed zero or more arguments which may beused in the execution of the body.
method —— A function which is defined inside a class body. Ifcalled as an attribute of an instance of that class, the methodwill get the instance object as its first argument (which isusually called self).

也就是说method是绑定在类里面的方法,再看下面这组对比示例:

def work(name):
    return "%s is eating!!!" % name

class Person:

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

    def sleep(self):
        return "%s is eating!!!" % self.name

print(work)
print(Person.sleep)

person = Person("xiaoming")
print(person.sleep)

打印结果为:

<function work at 0x00000000029FA620>
<function Person.sleep at 0x00000000029FAA60>
<bound method Person.sleep of <__main__.Person object at 0x00000000023FA860>>

可以看到,在我们实例化类过后,函数会变成这种bound method,即绑定实例的方法。

当然,@classmethod常常是用来设置类,比如举一个例子:

class Person:

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

    @classmethod
    def work(cls):
        cls.__init__(cls, "小明代工")
        print("%s is working!!!" % cls.name)

    def work_pub(self):
        print("%s is working!!!" % self.name)

xiaohong = Person("小红")
xiaohong.work()
xiaohong.work_pub()

打印结果为:

小明代工 is working!!!
小红 is working!!!

如果函数中没有包含实例必须的变量时可以使用staticmethod,无需传入实例,也不能传入。

class Person:

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

    @staticmethod
    def work(name):  # 不能传入self,所以整个函数内部也不会有self
        print("%s is working!!!" % name)
        
Person.work("xiaoming")
# 这里打印结果为 xiaoming is working!!!

这样做的好处就是不用实例化,可以外部直接调用work函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值