课堂上的其他键值对?

我是 python 的绝对初学者。我想知道我是否可以在 Class() 中使用额外的键值对?


class Users():   

    def __init__(self, first_name, last_name, **others):    

        for key, value in others.items():   

            self.key = value     

        self.first = first_name    

        self.last = last_name     

    def describe_user(self):      

        print("The user's first name is " + self.first)     

        print("The user's last name is " + self.last)       

        for key, value in others.items():     

            print("The user's " + key + " is " + value)


user1 = Users('Joseph', 'Wilson', age = '18', location = 'California')  

print(user1.location)   

user1.describe_user()

错误:


AttributeError: 'Users' object has no attribute 'location'   

NameError: name 'others' is not defined


慕仙森
浏览 153回答 1
1回答

守候你守候我

代替self.key = value你想用setattr(self, key, value)来设置属性。总之,你可以做这样的事情:class Users():    def __init__(self, first_name, last_name, **others):        for key, value in others.items():            setattr(self, key, value)        self.first = first_name        self.last = last_name    def describe_user(self):              for attribute in dir(self):            if attribute.startswith("__"):                continue            value = getattr(self, attribute)            if not isinstance(value, str):                continue            print("The user's " + attribute + " is " + value)user1 = Users('Joseph', 'Wilson', age='18', location='California')  print(user1.location)   user1.describe_user()您也可以轻松地使用 adict来存储信息。class Users():    def __init__(self, first_name, last_name, **others):        self.data = dict()        for key, value in others.items():            self.data[key] = value        self.data["first name"] = first_name        self.data["last name"] = last_name    def describe_user(self):              for key, value in self.data.items():            print("The user's {} is {}".format(key, value))user1 = Users('Joseph', 'Wilson', age=18, location='California')print(user1.data["location"])user1.describe_user()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python