gpt4 book ai didi

python - Python 类中 'cls' 和 'self' 之间的区别?

转载 作者:IT老高 更新时间:2023-10-28 12:12:22 26 4
gpt4 key购买 nike

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

例如:

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 说:

Function and method arguments:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

关于python - Python 类中 'cls' 和 'self' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4613000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com