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

问题描述 投票:1回答:1

根据Python docs

如果为派生类调用类方法,则派生类对象将作为隐式第一个参数传递。

因此我们可以得出结论,我们不需要使用类方法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 !

python object pycharm self class-method
1个回答
0
投票

当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

无警告!

© www.soinside.com 2019 - 2024. All rights reserved.