Python 静态方法 类方法

来源:互联网 发布:mac 双重认证 编辑:程序博客网 时间:2024/06/05 19:16
静态方法和实例方法的区别主要体现在两个方面:
1. 在外部调用静态方法时,可以使用"类名.方法名"的方式,也可以使用"对象名.方法名"的方式。而实例方法只有后面这种方式。也就是说,调用静态方法可以无需创建对象。
2. 静态方法在访问本类的成员时,只允许访问静态成员(即静态成员变量和静态方法),而不允许访问实例成员变量和实例方法;实例方法则无此限制。
3. 类方法可以被对象调用,也可以被实例调用;传入的都是类对象,主要用于工厂方法,具体的实现就交给子类处理
4. 静态方法参数没有实例参数 self, 也就不能调用实例参数
# coding: utf-8class Fruit(object):    version = 1.0  #静态对象    """docstring for Fruit"""    def __init__(self):        super(Fruit, self).__init__()        self.color = 'blue'    def is_clean(cls):        print cls.color        return True    @classmethod    def foo(cls):        #类方法可以被对象调用,也可以被实例调用;传入的都是类对象,主要用于工厂方法,具体的实现就交给子类处理        Fruit.version += 1        print cls.color        print 'calling this method foo()'    @staticmethod    def pish_color(color):        #静态方法参数没有实例参数 self, 也就不能调用实例参数        Fruit.color = color    def add_foo(self):        Fruit.version += 1if __name__ == "__main__":    o = Fruit()    o.is_clean()    # o.pish_color('Green')    # o.foo()    Fruit.foo()    # o.add_foo()    # print o.version    # o.foo()    # print o.version    # print Fruit.version


2 0