Python中静态方法与类方法比较

Python是一种面向对象的编程语言,故类的概念十分重要。其中python类中方法的定义有这样两种静态方法与类方法很相似。
定义一个类:
class Myclass:
    @staticmethod
    def foo1():
        print "this is static method"
    @classmethod
    def foo2(cls):
        print "this is class method"
调用:
mc = Myclass()
Myclass.foo1()
mc.foo1()
Myclass.foo2()
mc.foo2()
结果:
this is static method
this is static method
this is class method
this is class method
发现类的静态方法与类方法除了在定义类方法时多传了个参数,其他的没什么区别,无论是定义上还是调用上,都允许类和实例调用。
其实也就是上述的唯一不同(类方法定义时传递了一个cls参数),使类方法在一定的场景下很有用,该cls是类本身,如果我们要更新类属性时,类方法很有用
现在我们举个例子
定义类:
class Color(object):
    _color = (0, 0, 0);

    @classmethod
    def value(cls):
        if cls.__name__== 'Red':
            cls._color  = (255, 0, 0)

        elif cls.__name__ == 'Green':
            cls._color = (0, 255, 0)

        return cls._color

class Red(Color):
    pass

class Green(Color):
    pass

class UnknownColor(Color):
    pass

red = Red()
green = Green()
xcolor = UnknownColor()

print 'red = ', red.value()
print 'green = ', green.value()
print 'xcolor =', xcolor.value()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值