Python类中使用的“ cls”变量是什么? [英] What is the 'cls' variable used for in Python classes?

查看:68
本文介绍了Python类中使用的“ cls”变量是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在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)


推荐答案

自我 cls 之间的区别在 PEP 8 。正如Adrien所说,这不是强制性的。这是一种编码风格。 PEP 8 说:

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:


函数和方法参数

始终将 self 用作实例方法的第一个参数。

Always use self for the first argument to instance methods.

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

Always use cls for the first argument to class methods.

这篇关于Python类中使用的“ cls”变量是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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