gpt4 book ai didi

python - 类的方法是否应该至少有一个引用实例的参数?

转载 作者:行者123 更新时间:2023-12-01 02:37:28 25 4
gpt4 key购买 nike

Python 简而言之:

a method defined in a class body has a mandatory first parameter, conventionally named self , that refers to the instance on which you call the method.

类的方法是否应该至少有一个引用实例的参数?

创建不带任何参数的方法是一种不好的做法吗?

在类或类的实例上调用方法时始终使方法起作用是一个好习惯吗?

请注意,我不是在谈论静态方法或类方法,而是普通方法。

>>> class C5(object):
... def hello():
... print('Hello')
...
>>> C5.hello()
Hello
>>> C5().hello()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hello() takes 0 positional arguments but 1 was given

谢谢。

最佳答案

您应该始终将 self 作为类方法中的第一个参数。如果你想调用类方法而不创建类实例,需要编写以下内容:

class Foo:
@staticmethod
def hello():
print("Hi")

关于python - 类的方法是否应该至少有一个引用实例的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066695/

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