Ericson Willians
Ericson Willians

Reputation: 7845

How does Python know the instance variable without defining __init__?

Let us consider the following example:

class X:
    def run(self):
        print("An example.")

X().run()

The output is:

> An example.

But when we omit the reference to the instance:

class X:
    def run():
        print("An example.")

X().run()

The output is:

TypeError: run() takes 0 positional arguments but 1 was given

When we instantiate the class, __ new __ gets called and the instance is created, ok. But how it requires an instance without defining __ init __? (I'm surprised because, I've always written __ init __ thinking that it was responsible for defining the convention / self name for referencing the variable). I'm confused.

Upvotes: 3

Views: 380

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53535

When you call instance.run() if implicitly calls run(instance) which is why you're receiving the error:

TypeError: run() takes 0 positional arguments but 1 was given

That's also the reason why instance methods should have self as the first argument.

Second, you're using the old way of declaring a class - class X:
The new way1 is class X(object): but regardless if you're using the new/old annotation, the call X() will return an instance of the class, even in case you didn't define __init__.

And third, if you want to make it a class method you can either do what Pynchia suggested in the comment above (annotate the method with @staticmethod) or declare the method as a class method by specifying that the first argument is cls and annotating it as a class-method:

class X:

    @classmethod
    def run(cls):
        print "a"


X.run()  # prints a

1. According to Mark's comment below, in Python 3 we return to the "old way" of declaring a class. Good to know - thanks Mark!

Upvotes: 2

Related Questions