0
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? 🤔

3
  • When you create an instance of the class, the whole class has been defined. Also Python doesn't resolve references like say_hello() until it's actually executing the code. Commented Sep 27, 2022 at 6:28
  • 1
    Right. That's a key point. The code in the constructor is not executed until you create an object -- in the last line of your example. By that time, the class has been completely read and parsed. As long as say_hello has been defined by that point, it's all good. Commented Sep 27, 2022 at 6:34
  • "Defining a method inside the constructor" would look like self.say_hello = lambda: ... inside __init__. Which is not what you're doing. Commented Sep 27, 2022 at 6:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.