Python类中使用的“ cls”变量是什么?

编程入门 行业动态 更新时间:2024-10-11 19:13:35
本文介绍了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”变量是什么?

本文发布于:2023-11-27 22:37:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   类中   Python   cls

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!