Home > Mobile >  Python Classes: behavior of calling class methods inside constructor
Python Classes: behavior of calling class methods inside constructor

Time:09-28

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?

  • Related