• 静态方法和类成员方法(Python)


        静态方法和成员方法分别在创建时分别被装入Staticmethod 类型和 Classmethod类型的对象中。静态方法的定义没有 self参数,且能够被类本身直接调用,类方法在定义时需要名为 cls的类似于self的参数,类成员方法可以直接用类的具体对象调用。但cls参数是自动被绑定到类的,请看下面例子:

     
     1 __metaclass__ = type
     2  
     3 class Myclass:
     4  
     5 def smeth():
     6 print "This is a static method"
     7 smeth = staticmethod(smeth)
     8  
     9 def cmeth(cls):
    10 print "This is a class method of", cls
    11 cmeth = classmethod(cmeth)
        手动包装和替换方法的技术看起来有点单调。在Python2.4中,为这样的包装方法引入了一个叫做装饰器(decorators)的新语法(它能够对任何可调用的对象进行包装,即能够用于方法也能用于函数)。使用@操作符,在方法(或函数)的上方将装饰器列出,从而指定一个或者更多的装饰器(多个装饰器在应用时的顺序与指定顺序相反)
     1 __metaclass__ = type
     2  
     3 class Myclass:
     4  
     5 @staticmethod
     6 def smeth():
     7 print "This is a static method"
     8  
     9 @classmethod
    10 def cmeth(cls):
    11 print "This is a class method of", cls
        定义了这些方法后,就可以像下面的例子那样使用(例子中没有实例化类):
    >>>Myclass.smeth()
    This is a static method
    >>>Myclass.cmeth()
    This is a class method of <class '__main__.Myclass'>
  • 相关阅读:
    模型
    smarty变量
    smarty变量调节器
    分页
    表单验证(注册)
    php数据库访问
    php面向对象 继承
    php 面向对象
    php正则数组
    php 函数
  • 原文地址:https://www.cnblogs.com/tsbc/p/4081471.html
Copyright © 2020-2023  润新知