我绝对是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
答案 0 :(得分:0)
代替
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()
您也可以轻松地使用dict
来存储信息。
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()