Five, Python 5 facing the object, the class methods, and static methods

5, class methods, and static methods

Description : class methods and static methods similar, they are recommended to use class to call (available objects to call)

1) Class Methods

The definition of class method :

  • Use @classmethod modified
  • The first parameter is defined as a method cls, this method is invoked by the class parameter are automatically bound
class Tiger:
    # 类方法:1、用 @classmethod 修饰;2、定义 cls 形参
    @classmethod
    def info(cls):
        print('info类方法')
        print(cls)
        
print(Tiger)
print('-'*30)

Tiger.info()     # 类方法属于类本身,可用类调用。类方法的第一个参数 cls 绑定到调用该方法的类
print('-'*30)

t = Tiger()
t.info()         # 对象调用类方法,实际上也相当于用类调用类方法,同样也会执行将第一个参数绑定当前类
<class '__main__.Tiger'>
------------------------------
info类方法
<class '__main__.Tiger'>
------------------------------
info类方法
<class '__main__.Tiger'>

Compare :

  • Whether it is a class method invocation or class instance calls are automatically bound
  • Examples of the method when the object is automatically bound with the call when the call is not automatically bound by class, parameter passing requires

2) static method

Define a static method :

  • Use @staticmethod modified

  • Static method is equivalent to a function, not automatically binding

    class Tiger:
        # 静态方法:用 @staticmethod
        @staticmethod
        def info1():
            print('info1静态方法')
        
        @staticmethod  
        def info2(p):
            print('info2静态方法')
            print(p)
    
    • Class static method call

      Tiger.info1()             # 类调用静态方法(无参数时)
      print('-'*30)
      
      Tiger.info2('python')     # 类调用静态方法(有参数时),需要传入参数
      
      info1静态方法
      ------------------------------
      info2静态方法
      python
      
    • Object calls the static method

      t = Tiger()
      
      t.info1()          # 对象调用静态方法(无参数时)
      print('-'*30)
      
      t.info2('python')  # 对象调用静态方法(有参数时),需要传入参数
      print('-'*30)
      
      info1静态方法
      ------------------------------
      info2静态方法
      python
      

3) Summary:

Examples of methods Class Methods Static method
Object calls Automatic Binding Automatic Binding Do not automatically binding
Class call Do not automatically binding Automatic Binding Do not automatically binding

Guess you like

Origin blog.csdn.net/qq_36512295/article/details/94547769