• python3 中的cls和self的区别 静态方法和类方法的区别


     


    一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。

    而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。

    这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁

    class A():
            a='1'
    
            @staticmethod
            def foo1(name):
                    print("hello,%s"%(name))
            def foo2(self,name):
                    print("hello,%s"%(name))
    
            @classmethod
            def foo3(cls,name):
                    print("hello,%s"%(name))
    
    
    a=A()
    a.foo1('mamq')
    A.foo1('mamq')
    print("---------------------"*20)
    a.foo2('mamq')
    #A.foo2('mamq')
    
    a.foo3('foo3')
    A.foo3('foo3')

    首先定义一个类A,类A中有三个函数,foo1为静态函数,用@staticmethod装饰器装饰,这种方法与类有某种关系但不需要使用到实例或者类来参与。如下两种方法都可以正常输出,也就是说既可以作为类的方法使用,也可以作为类的实例的方法使用。

    1.  
      a = A()
    2.  
      a.foo1('mamq') # 输出: hello mamq
    3.  
      A.foo1('mamq')# 输出: hello mamq

    foo2为正常的函数,是类的实例的函数,只能通过a调用。

    1.  
      a.foo2('mamq') # 输出: hello mamq
    2.  
      A.foo2('mamq') #   报错:普通类方法不能这样来调用 

    foo3为类函数,cls作为第一个参数用来表示类本身. 在类方法中用到,类方法是只与类本身有关而与实例无关的方法。如下两种方法都可以正常输出。

    1.  
      a.foo3('mamq') # 输出: hello mamq
    2.  
      A.foo3('mamq') # 输出: hello mamq
     

    在个人多次试验后,目前只发现了 类方法有防止硬解码的效果,其他情况下,类方法都可以用静态方法代替

  • 相关阅读:
    LeetCode 重排链表算法题解 All In One
    上海图书馆 & 上海图书馆东馆 All In One
    北美 CS 专业 New Grad 工资组成部分 All In One
    Go Gin errors All In One
    人邮学院 All In One
    Leetcode 1512. 好数对的数目
    VS中创建和使用c++的dll动态库(转)
    通过HWND获得CWnd指针/通过CWnd获取HWND
    读文件使用QProgressBar显示进度
    R语言中apply函数的用法
  • 原文地址:https://www.cnblogs.com/ZFBG/p/11459551.html
Copyright © 2020-2023  润新知