静态方法和类成员方法

静态方法和类成员方法分别正在建立时分别装入 staticmethod 类型和 classmethod 类型的对象
使用装饰器(decorator)语法
'''
#老方法
__metaclass__ = type

class MyClass:

    def smeth():                      #静态方法定义没有self参数,且可以被类自己直接调用
        print 'This is a static method'
    smeth = staticmethod(smeth)       #静态方法在建立时装入 staticmethod 类型

    def cmeth(cls):                   #类方法在定义时,须要名为 cls 的相似于 self 的参数,能够用类的对象调用
        print 'This is a class method'
    cemth = classmethod(cmeth)        #类成员方法在建立时换入 classmethod 类型

'''

#装饰器
#它能对任何可调用的对象进行包装,既可以用于方法也可以用于函数
#使 @ 操做符,在方法(或函数)的上方将装饰器列出,从而指定一个或者更多的装饰器(多个装饰器在应用时的顺序与指定顺序相反)

__metaclass__= type

class MyClass:

    @staticmethod  #定义静态方法
    def smeth():
        print 'This is a static method'

    @classmethod   #定义类方法
    def cmethd(cls):
        print 'This is a class method',cls

    def instancefun(self):   #实例方法
        print '实例方法'

    def function():          #普通方法
        print '普通方法'


mc =  MyClass()

MyClass.smeth()              #类和对象均可以调用静态方法
mc.smeth()
MyClass.cmethd()             #类方法也能够直接被类调用
MyClass().cmethd()           #类方法被对象调用
mc.instancefun()             #对象调用实例方法
mc.cmethd()                  #对象调用类方法

#MyClass.instancefun()       #类调用实例方法,报错
#mc.function()               #对象调用普通方法,报错
相关文章
相关标签/搜索