Search code examples
pythonattributeerror

Passing a dictionary to the __init__ function and trying to access it later gives an error, why?


class User:
    """a simple attempt to model a User"""
    
    def __init__(self, first, last, **user_info):
        self.user_info["first name"] = first
        self.user_info["last name"] = last


    def describe_user(self):
        for k,v in self.user_info.items():
            print(f"user's {k} is: {v}")


    def greet_user(self):
        print(f'\nHello {self.user_info["first name"].title()}')


user_1 = User("ahmed","ibrahim", age=22, gender="Male", hight="tall enough", location="unknown")
user_1.describe_user()

Error:

AttributeError: 'User' object has no attribute 'user_info'

Solution

  • You'd have to first copy that dict into self

    def __init__(self, first, last, **user_info):
        self.user_info = user_info
        self.user_info["first name"] = first
        self.user_info["last name"] = last