edhedges
edhedges

Reputation: 2718

Should it be possible to call an instance method of a class without creating a new object of that class?

I can do this and I don't have any issues:

class MyClass:
    def introduce(self):
        print("Hello, I am %s, and my name is " %(self))

MyClass.introduce(0)
MyClass().introduce()

I'm using Visual Studio and Python 3.4.1. I don't understand why this doesn't throw an error since I'm basically setting the value of this. Is this a feature and I just shouldn't be doing this? Should I be checking if self is actually an instance of MyClass?

Upvotes: 0

Views: 59

Answers (1)

tburette
tburette

Reputation: 181

In Python 3 when you do MyClass.introduce() introduce is not linked to any object. It's considered as a (standalone) function like any other function you would declare by itself. The fact that it is declared within a class is not relevant here. introduce is therefore called like any function: a function with one parameter.

When you do MyClass().introduce() (notice the first set of parentheses) introduce is considered as a method belonging to an object which is an instance of class MyClass hence the regular OO behavior of adding automatically the self parameter.

Note that this is different for python 2. In python 2 there is a check to verify that when called, the effective argument passed for the self parameter is indeed an object of the correct type, i.e. an instance of MyClass. If you try MyClass.introduce(0) in Python 2 you'll get: unbound method introduce() must be called with MyClass instance as first argument (got int instance instead). This check doesn't exist in Python 3 anymore because the notion of unbound method no longer exist.

Upvotes: 2

Related Questions