python中cls和self的不同及使用

python中cls和self的不同及使用,第1张

python中cls和self的不同及使用

文章目录

1.在类中不同方法2.cls是什么3.cls和self的不同4.补充写在最后
在讲正式内容之前,先讲一下背景知识

1.在类中不同方法
    静态方法类方法实例方法

这里就详细说一下类方法

类方法绑定到一个类而不是类的对象。这些方法可以在没有类的实例的情况下调用。我们可以使用classmethod()方法或装饰器@classmethod创建类方法。类方法接受cls作为参数,指示该方法指向类而不是对象实例。

class Sample:
  var = "Class Variable"
 
  @classmethod
  def method(cls):
    print(cls.var)
 
Sample.method()

输出:

Class Variable
2.cls是什么


  cls就表示此class的意思即Test,将cls用于类方法中,表示此方法属于类方法,如about(cls),可以调用类属性info
(ps:self表示实例的意思,它们都是python中的关键字,改变命名并不会改变它们的功能。)
  一个稍微复杂一点的实例是:

class Test:
    info="this is the class storing name and score"#类属性
    def __init__(self,name,score):
        self.name=name
        self.score=score

    def search(self):#实例方法
        print(f"name:{self.name},score:{self.score}")

    @classmethod
    def about(cls):#类方法
        print(cls.info)
        
    @staticmethod
    def method():#静态方法
        print("this is a stactic method")
        
Test.method()#静态方法

obj1=Test("alex",99)
obj1.search()#must have ()#实例方法

Test.about()#类方法

输出

3.cls和self的不同

  cls指的是类,而 self 指的是实例。使用cls关键字,我们只能访问类的成员,而使用 self 关键字,我们可以访问实例变量和类属性。
 使用cls,我们无法访问类中的实例变量。cls作为参数传递给类方法,而 self 作为参数传递给实例方法。如果我们使用self初始化变量,它们的作用域就是实例的作用域。但是,使用cls初始化的变量将类作为其作用域。

4.补充

 cls()还可以调用实例方法,下面:

class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):  # 类方法
        print ('func2')
        print (cls.bar)
        cls().func1()   # 调用 foo 方法
 
A.func2()               # 不需要实例化

输出:

func2
1
foo

其中cls().fun1()中的cls()相当于实例化了对象,具体的原理等以后用到了我再深究吧

写在最后

(不知道我这样,花费这么多时间搞懂一个点有什么consequnce,我只知道我想弄清楚)

参考:
pythonpool.com/python-cls-vs-self/
https://blog.csdn.net/soulesstitan/article/details/102406953

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5720365.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存