有关staticmethod classmethod

class Test:
    def __init__(self, id):
        self.id = id

    def printd(self):
        print self.id
        print('Arg in Method: ', self)

    @staticmethod
    def smethod(*arg):
        print('Arg in staticMethod: ', arg)

    @classmethod
    def cmetod(*arg):
        print("Arg in classMethod: ", arg)

#classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入
#staticmethod 基本上和一个全局函数差不多,不会隐式地传入任何参数
test = Test(1)
test.printd()
test2 = Test(2)
test2.printd()
test.cmetod()
Test.cmetod()
Test.smethod()
test.smethod()

输出:

1
('Arg in Method: ', <method.Test instance at 0x00000000028D9208>)
2
('Arg in Method: ', <method.Test instance at 0x00000000028E3388>)
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in staticMethod: ', ())
('Arg in staticMethod: ', ())



结论:

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值