在 Python 中从字典设置实例属性

在 Python 中从字典设置实例属性

Set instance attributes from a Dictionary in Python

从字典中设置实例属性:

  1. __init__()在类的方法中迭代字典的项目。
  2. 使用该setattr方法将每个键值对设置为实例属性。
主程序
class Developer(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 50 print(bob.language) # 👉️ Python

__init__()方法采用字典并将其键值对设置为实例属性。

我们使用for循环来遍历字典的项目。

dict.items方法返回字典
项((键,值)对)的新视图。

主程序
my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} # 👇️ dict_items([('name', 'bobbyhadz'), ('salary', 50), ('language', 'Python')]) print(my_dict.items())

在每次迭代中,我们使用
setattr()函数将每个键值对设置为实例的一个属性。

主程序
for key, value in dictionary.items(): setattr(self, key, value)

setattr()函数将对象、属性名称和值作为参数。

您还可以调整__init__()方法以在字典后采用关键字参数。

主程序
class Developer(): def __init__(self, dictionary, **kwargs): # 👇️ {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} print(dictionary) # 👇️ {'tasks': ['develop', 'test'], 'age': 30} print(kwargs) for key, value in dictionary.items(): setattr(self, key, value) for key, value in kwargs.items(): setattr(self, key, value) my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict, tasks=['develop', 'test'], age=30) print(bob.name) # 👉️ bobbyhadz print(bob.tasks) # 👉️ ['develop', 'test']

该类的__init__()方法可选择在字典后采用关键字参数。

但是,如果您没有,则不需要传递关键字参数。

如果您的字典包含带空格的键,请使用该str.replace()方法将每个空格替换为下划线。

主程序
class Developer(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, str(key).replace(' ', '_'), value) my_dict = {'first name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.first_name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 50 print(bob.language) # 👉️ Python

first name键包含一个空格,因此我们使用该方法str.replace()将字典键中的任何空格替换为下划线。

If you get linting errors when you try to access attributes on each instance,
e.g. “Instance of ‘Developer’ type has no ‘X’ member”, initialize the attributes
to None.

main.py
class Developer(): def __init__(self, dictionary): self.name = None self.salary = None self.language = None for key, value in dictionary.items(): setattr(self, str(key).replace(' ', '_'), value) my_dict = {'first name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 50 print(bob.language) # 👉️ Python

We initialized all attributes to None, so we can access the attributes on each
instance without getting linting errors.

An alternative approach to consider is to define the properties in the
__init__() method and unpack the dictionary’s key-value pairs when
instantiating the class.

main.py
class Developer(): def __init__(self, name, salary, language): self.name = name self.salary = salary self.language = language my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(**my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 50 print(bob.language) # 👉️ Python

We used the ** operator to unpack the key-value pairs of the dictionary when
instantiating the class.

You can imagine that the dictionary’s key-value pairs got passed as keyword
arguments to the class, e.g.
Developer(name='bobbyhadz', salary=50, language='Python').