Difference between 'cls' and 'self' in Python classes?

后端 未结 5 1967
北海茫月
北海茫月 2020-11-28 00:43

Why is cls sometimes used instead of self as an argument in Python classes?

For example:

class Person:
    def __init__(sel         


        
5条回答
  •  醉话见心
    2020-11-28 01:10

    Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

    -Python Tricks

提交回复
热议问题