star
star

Reputation: 284

how value is passed from __init__ method in pyhton as it dose not return anyhting

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

bob = Person1('bob', 25)

__init__ does not return anything so how are the values of properties name and age passed from __init__ function to the variable bob after assigning the properties name and age to the empty object self?

Upvotes: 0

Views: 252

Answers (1)

chepner
chepner

Reputation: 531878

bob = Person1('bob', 25) is really equivalent to something like

rv = Person1.__new__(Person1, 'bob', 25)
if isinstance(rv, Person1):
    rv.__init__('bob', 25)
bob = rv

Calling a class doesn't immediately call the __init__ method. The class's __new__ method is called first to actually create the new instance, and if __new__ returns an instance of the class passed as the first argument, then __init__ is called before returning the value.


Going a step further, this is all encapsulated in type.__call__, so really the call to Person1('bob', 25) is something like

bob = type.__call__(Person1, 'bob', 25)  # Person1 is an instance of type

where type.__call__ is what calls Person1.__new__ and, if appropriate, Person.__init__, and returns the resulting object for it to be assigned to bob.

Upvotes: 4

Related Questions