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

后端 未结 5 1968
北海茫月
北海茫月 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:03

    The distinction between "self" and "cls" is defined in PEP 8 . As Adrien said, this is not a mandatory. It's a coding style. PEP 8 says:

    Function and method arguments:

    Always use self for the first argument to instance methods.

    Always use cls for the first argument to class methods.

提交回复
热议问题