101
101

Reputation: 1

Calling a method of a class before creating an object

Let's say we have a class, and we are calling it's method before creating an object:

class ParentClass:  
    def MyMethod(self):
        self.a=5
        print("I am Method")

ParentClass.MyMethod(ParentClass)

Why do we get a result? Also, why hasattr(ParentClass,'a') is showing that instance variable is created?

Upvotes: 0

Views: 420

Answers (1)

chepner
chepner

Reputation: 532518

You get a result because you ParentClass.MyMethod evaluates to a regular function that takes one argument, which you supplied. The function doesn't care what the type of self is, as long as you can define an attribute named a for it. The result of ParentClass.MyMethod(ParentClass) is to add an attribute named a to ParentClass.

ParentClass().MyMethod, on the other hand, produces an instance of method that wraps the function, due to the descriptor protocol. The method, when called, simply calls the function with the instance as the first argument and the rest of its own arguments. Because the function doesn't expect any more arguments, you would get a TypeError.

Upvotes: 2

Related Questions