gpt4 book ai didi

python - PyCharm 警告我为由 classmethod 函数创建的 classmethod 创建对象

转载 作者:行者123 更新时间:2023-12-01 00:22:05 28 4
gpt4 key购买 nike

根据Python docs :

If a class method is called for a derived class, the derived class object is passed as the implied first argument.

因此我们可以得出结论,我们不需要使用类方法 function 创建对象。但我不知道为什么 PyCharm 会给我这个警告,而它执行代码完全没有问题。

这是代码:

class Fruit:
def sayhi(self):
print("Hi, I'm a fruit")


Fruit.sayhi = classmethod(Fruit.sayhi)
Fruit.sayhi()enter code here

这是警告

Parameter self unfilled

Parameter self unfilled !

最佳答案

当 PyCharm 向您发出这些警告时,它会通过查看类定义来确定 sayhi 函数的工作方式。根据您的类定义,sayhi 需要一个您尚未填充的参数 self。在第 6 行,您已将 sayhi 重新分配为类方法,但是,就 PyCharm 而言,这是在类定义之外,因此它是“一切皆有可能”的领域,并且不会费心尝试根据该代码的作用做出假设。如果您希望 PyCharm 知道 sayhi 是一个类方法,您应该在类定义中指定它。例如,使用classmethod作为装饰器

class Fruit:
@classmethod
def sayhi(self):
print("Hi, im a fruit")


Fruit.sayhi()

enter image description here

没有警告!

关于python - PyCharm 警告我为由 classmethod 函数创建的 classmethod 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890089/

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