Confusion with dynamically adding methods in class

class User:
    pass

# Add instance attributes dynamically
jane = User()
jane.name = "Jane Doe"
jane.job = "Data Engineer"
jane.__dict__  # {'name': 'Jane Doe', 'job': 'Data Engineer'}

# Add methods dynamically
def __init__(self, name, job):
    self.name = name
    self.job = job

User.__init__ = __init__
User.__dict__  # mappingproxy({'__init__': <function __init__ at 0x1036ccae0>})

linda = User("Linda Smith", "Team Lead")
linda.__dict__  # {'name': 'Linda Smith', 'job': 'Team Lead'}

can someone explain me this code from def __init__(self, name, job): . I learnt init is used to add instance attribute, then why this comment says add method dynamically. and what is User.__init__ = __init__

You’ve made a class called User that doesn’t have an __init__ method.

You’re then adding such a method afterwards by making a function called __init__ that has the required parameter list and adding that function to the class. That’s what User.__init__ = __init__ does. It adds the __init__ function to the User class. Now the class has an __init__ method.

Why would you want to add methods dynamically? Well, it has its uses, but I’ve never needed to do it.

1 Like