zoukankan      html  css  js  c++  java
  • staticmethod classmethod修饰符

    一、staticmethod(function) 

    Return a static method for function.
    A static method does not receive an implicit first argument. To declare a static method, use this idiom:

    class Sing():
        @staticmethod
        def sayHello():
            print "hello world"
    
        def sayNo():
            print "no"
    
    if __name__ == '__main__':
        Sing.sayHello()
        Sing.sayNo()

    Sing.sayNo报错如下:

    TypeError: unbound method sayNo() must be called with Sing instance as first argument (got nothing instead)
    sayNo()方法非静态方法,需要先将对象Sing实例化才能调用该方法
    而sayHello()方法不报错,因为staticmethod修饰
    下面方法才是对的:

    class Sing():
        @staticmethod
        def sayHello():
            print "hello world"
    
        def sayNo(self):
            print "no"
    
    if __name__ == '__main__':
        Sing.sayHello()
        sing = Sing()
        sing.sayNo()

    二、classmethod(function) 

    Return a class method for function.
    A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

    class Sing():
        @classmethod
        def sayHello(self):
            print "hello world"
    
        def sayNo(self):
            print "no"
    
    if __name__ == '__main__':
        Sing.sayHello()
        sing = Sing()
        sing.sayNo()
        

    注意:staticmethod修饰的方法不需要接self参数,而classmethod修饰的方法则需要接self参数;

    三、@property修饰符(新式类特有,新式类即接object定义的类)
    修饰为类的属性,如下为不加@property修饰符的类的定义:

    class C(object):
        def __init__(self):
            self._x = None
    
        def getx(self):
            return self._x
        def setx(self, value):
            self._x = value
        def delx(self):
            del self._x
        x = property(getx, setx, delx, "I'm the 'x' property.")

    通过@property修饰符修饰的类的定义:(从Python2.6开始引入setter,deleter,getter属性)

    class C(object):
        def __init__(self): self._x = None
    
        @property
        def x(self):
            """I'm the 'x' property."""
            return self._x
    
        @x.setter
        def x(self, value):
            self._x = value
    
        @x.deleter
        def x(self):
            del self._x
  • 相关阅读:
    (android高仿系列)今日头条 --新闻阅读器 (三) 完结 、总结 篇
    今日头条 --新闻阅读器
    免费新闻娱乐接口文档
    [代码片段] Android百度地图定位收索取周边在列表中展示并选择
    引用其它布局
    关于推广个人博客的经验_博客推广
    博客推广方法技巧
    android项目解刨之时间轴
    Android小项目:计算器
    Android项目技术总结:网络连接总结
  • 原文地址:https://www.cnblogs.com/forilen/p/4465439.html
Copyright © 2011-2022 走看看