Python 类中“cls"和“self"之间的区别? [英] Difference between 'cls' and 'self' in Python classes?

查看:34
本文介绍了Python 类中“cls"和“self"之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在 Python 类中有时使用 cls 而不是 self 作为参数?

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

例如:

class Person:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    @classmethod
    def from_fullname(cls, fullname):
        cls.firstname, cls.lastname = fullname.split(' ', 1)

推荐答案

"self""cls" 的区别定义在 PEP 8 .正如 Adrien 所说,这不是强制性的.这是一种编码风格.PEP 8 说:

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

函数和方法参数:

总是使用 self 作为实例方法的第一个参数.

Always use self for the first argument to instance methods.

始终使用 cls 作为类方法的第一个参数.

Always use cls for the first argument to class methods.

这篇关于Python 类中“cls"和“self"之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆