Search code examples
pythonobjectpycharmselfclass-method

PyCharm warns me to create an object for a classmethod made by classmethod function


According to Python docs:

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

So we can conclude that we don't need to create an object using class method function . But I don't know why PyCharm gives me this warning, while it executes the code with no problem at all.

This is the code:

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


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

And this is the warning

Parameter self unfilled

Parameter self unfilled !


Solution

  • When PyCharm gives you these warnings, it determines how the sayhi function works by looking at the class definition. According to your class definition, sayhi requires an argument self that you have not filled. On line 6 you have re-assigned sayhi as a classmethod, however, as far as PyCharm is concerned, this is outside of the class definition so it is the "anything goes" territory and it won't bother trying to make assumptions based on what that code does. If you want PyCharm to know that sayhi is a class method, you should specify that in the class definiton. For example, by using classmethod as a decorator

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

    enter image description here

    No warning!