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

来源:互联网 发布:网络直播对大学生影响 编辑:程序博客网 时间:2024/05/15 22:57
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()
0 0
原创粉丝点击