将字典传递给__init__函数并稍后尝试访问它会产生错误,为什么?

问题描述

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()

错误

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

解决方法

您必须先将该字典复制到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