Cristian San
Cristian San

Reputation: 19

Python Classes: behavior of calling class methods inside constructor

class User:

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.say_hello()

    def say_hello(self):
        print(f"Hi my name is {self.name} and I am {self.age}")

user = User("Cristian", 19)

output:

**Hi my name is Cristian and I am 19**

Hello! I have a question about this code. We know that when we create an instance of a class, the constructor is executed, right?; in the code we can see a say_hello method that is called inside the constructor, how is this possible if the say_hello method is created after the constructor, how can we call something that is not previously defined? 🤔

Upvotes: 0

Views: 365

Answers (1)

Rupal Shah
Rupal Shah

Reputation: 339

As per your code, the say_hello() method is defined before it is called. The say_hello() is called from __init__() that's true, but __init__() is called when you are creating your object user = User("Cristian", 19)

So the statement responsible for calling say_hello() is creation of object and definition of say_hello() appears before it is called.

Hope this suffice your query.

Upvotes: 1

Related Questions