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()
添加回答
举报