zoukankan      html  css  js  c++  java
  • Python Static Method

    How to define a static method in Python?
    Demo:

    #!/usr/bin/python2.7
    #coding:utf-8
    # FileName: test.py
    # Author: lxw
    # Date: 2015-07-03
    
    #Inside a class, we can define attributes and methods
    class Robot:
        '''Robot class.
    
        Attributes and Methods'''
        population = 0
        def __init__(self, name):
            self.name = name
            Robot.population += 1
            print('(Initialize {0})'.format(self.name))
    
        def __del__(self):
            Robot.population -= 1
            if Robot.population == 0:
                print('{0} was the last one.'.format(self.name))
            else:
                print('There are still {0:d} robots working.'.format(Robot.population))
    
        def sayHi(self):
            print('Greetings, my master call me {0}.'.format(self.name))
    
        '''
        #The following class method is OK.
        @classmethod
        def howMany(cls):   #cls is essential.
            print('We have {0:d} robots.'.format(cls.population))
        '''
    
        '''
        #The following static method is OK.
        @staticmethod
        def howMany():
            print('We have {0:d} robots.'.format(Robot.population))
        '''
    
        #The following class method is OK.
        def howMany(cls):   #cls is essential.
            print('We have {0:d} robots.'.format(cls.population))
        howMany = classmethod(howMany)
    
        '''
        #The following static method is OK.
        def howMany():
            print('We have {0:d} robots.'.format(Robot.population))
        howMany = staticmethod(howMany)
        '''
        
    
    def main():
        robot1 = Robot("lxw1")
        robot1.sayHi()
        #staticmethod/classmethod 都既可以使用类名访问,也可以使用对象名访问, 但classmethod在定义时需要cls参数
        Robot.howMany()
        robot1.howMany()
        
        robot2 = Robot("lxw2")
        robot2.sayHi()
        Robot.howMany()
        robot2.howMany()
    
    if __name__ == '__main__':
        main()
    else:
        print("Being imported as a module.")

    Differences between staticmethod and classmethod:

    classmethod:

    Its definition is mutable via inheritance, Its definition follows subclass, not parent class, via inheritance, can be

    overridden by subclass. It is important when you want to write a factory method and by this custom attribute(s)

    can be attached in a class.

    staticmethod:

    Its definition is immutable via inheritance. 类似其他语言中的static方法。

  • 相关阅读:
    ASP.NET调用word开发环境下正常,iis下报错
    关于CSS的两本书的感觉
    蓝牙模块在HHARM2410上的移植
    关于Activity和Task的设计思路和方法
    用蓝牙连接debian和诺基亚手机
    15.2 连接蓝牙设备
    蓝芽:Linux与手机(at,ftp)
    UBUTUN 通过蓝牙连接Hoary和诺基亚手机
    php class类用法总结 Leone
    提高PHP编程效率的53个要点 Leone
  • 原文地址:https://www.cnblogs.com/lxw0109/p/python_static_method.html
Copyright © 2011-2022 走看看