• python中的cls到底指的是什么


    python中的cls到底指的是什么,与self有什么区别?

    作者:秦风
    链接:https://www.zhihu.com/question/49660420/answer/335991541

     

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

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

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

    1.  
      class A(object):
    2.  
      a = 'a'
    3.  
      @staticmethod
    4.  
      def foo1(name):
    5.  
      print 'hello', name
    6.  
      def foo2(self, name):
    7.  
      print 'hello', name
    8.  
      @classmethod
    9.  
      def foo3(cls, name):
    10.  
      print 'hello', name

    首先定义一个类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') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)

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

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

    但是通过例子发现staticmethod与classmethod的使用方法和输出结果相同,再看看这两种方法的区别。

    既然@staticmethod和@classmethod都可以直接类名.方法名()来调用,那他们有什么区别呢
    从它们的使用上来看,
    @staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
    @classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
    如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
    而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。

    也就是说在classmethod中可以调用类中定义的其他方法、类的属性,但staticmethod只能通过A.a调用类的属性,但无法通过在该函数内部调用A.foo2()。修改上面的代码加以说明:

    1.  
      class A(object):
    2.  
      a = 'a'
    3.  
      @staticmethod
    4.  
      def foo1(name):
    5.  
      print 'hello', name
    6.  
      print A.a # 正常
    7.  
      print A.foo2('mamq') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)
    8.  
      def foo2(self, name):
    9.  
      print 'hello', name
    10.  
      @classmethod
    11.  
      def foo3(cls, name):
    12.  
      print 'hello', name
    13.  
      print A.a
    14.  
      print cls().foo2(name)
  • 相关阅读:
    python3.0与python2.0有哪些不同
    python常用内置模块,执行系统命令的模块
    06python 之基本数据类型
    python语言简介、解释器、字符编码介绍
    http协议&接口规范&接口测试入门
    基于APPIUM测试微信公众号的UI自动化测试框架(结合Allure2测试报告框架)
    SQL注入工具sqlmap的注入过程记录
    unittest框架
    测试转型之路--学习ing
    Tomcat分析-启动过程
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/10965686.html
Copyright © 2020-2023  润新知