为了账号安全,请及时绑定邮箱和手机立即绑定

课堂上的其他键值对?

课堂上的其他键值对?

慕仙森 2021-09-25 18:31:41
我是 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
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

代替


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


查看完整回答
反对 回复 2021-09-25
  • 1 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信