0005python中的静态方法和类方法

#!/usr/bin/env python
# coding=utf-8

__metaclass__ = type

class StaticMethod:
@staticmethod
def foo():
print "This is static method foo()."

class ClassMethod:
@classmethod
def bar(cls):
print "This is class method bar()."
print "bar() is part of class:", cls.__name__

if __name__ == "__main__":
static_foo = StaticMethod() #实例化
static_foo.foo() #实例调用静态方法
StaticMethod.foo() #通过类来调用静态方法
print "********"
class_bar = ClassMethod()
class_bar.bar()
ClassMethod.bar()

 

C:\Users\Administrator>python d:\aa.py
This is static method foo().
This is static method foo().
********
This is class method bar().
bar() is part of class: ClassMethod
This is class method bar().
bar() is part of class: ClassMethod

 

posted @ 2017-02-07 16:49  紫色物语  阅读(150)  评论(0编辑  收藏  举报