[英]additional key-value pairs in class?
我是 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
代替
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.