# filename: class_static.py

class Parent:
    name = "I'm the parent"

    @staticmethod
    def print_name_by_static():
        print(Parent.name)

    @classmethod
    def print_name_by_class(cls):
        print(cls.name)

class Child(Parent):
    pass #(1)
    # name = "I'm the child" #(2)

if __name__ == "__main__":
    p = Parent()
    p.print_name_by_static()
    p.print_name_by_class()
    Parent.print_name_by_static()
    Parent.print_name_by_class()

    print('=====================')

    c = Child()
    c.print_name_by_static()
    c.print_name_by_class()
    Child.print_name_by_static()
    Child.print_name_by_class()

运行结果:

>>> 
I'm the parent
I'm the parent
I'm the parent
I'm the parent
=====================
I'm the parent
I'm the parent
I'm the parent
I'm the parent

去掉注释(2),注释掉(1):

>>> 
I'm the parent
I'm the parent
I'm the parent
I'm the parent
=====================
I'm the parent
I'm the child
I'm the parent
I'm the child

通过上面得出的结果可以分析:

由@staticmethod修饰的方法叫静态方法,由@classmethod修饰的方法叫类方法。
共同点:
静态方法和类方法都可以用类或其实例进行调用。
不同点:
类方法在定义时,需要名为cls的类似于self的参数。cls参数是自动绑定到当前类的。

posted on 2013-04-28 01:21  101010  阅读(229)  评论(0编辑  收藏  举报