星期一, 十一月 24, 2008

python中类的静态方法(方法修饰符)

python中除了最常用类实例方法外,还有类方法和静态方法两种。
##############################
#类方法
##############################
class Foo:
        str = "I'm a static method."

        @classmethod     #方法修饰符――指明该方法为类方法
        def bar(cls):         #cls为类对象,可以通过他引用静态数据成员
            print cls.str
           
Foo.bar()                      #静态方法的调用方法一:类对象.方法名()
o1 = Foo()
o1.bar()                        #静态方法的调用方法二:类实例对象.方法名()

##############################
#静态方法
##############################
class Foo:
        str = "I'm a static method."

        @staticmethod
        def bar():                        #没有cls参数
            print Foo.str
           
Foo.bar()
o1 = Foo()
o1.bar()

更多见

Python类的基础入门知识

没有评论: