我绝对是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()

关于python - 类中的其他键值对?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53926403/

10-12 21:01