When we're in Python Write a class when , If some member variables need to be named and assigned with a dictionary , How to operate at this time ? This scenario is most common from a file ( such as json、npz Something like that ) Read dictionary variables into memory , Then assign a value to the member variable of a class , Or instance variables that have been generated .
__dict__
Define member variables stay python Directly supported in __dict__.update()
In this way , Avoid right locals()、vars() and eval() Use of functions , We can look directly at such a case :
In [1]: dict_a = {
'a':1, 'b':2}
In [2]: dict_b = {
'c':3}
In [3]: class D(object):
...: def __init__(self):
...: self.d = 4
...: self.__dict__.update(dict_a)
...: self.__dict__.update(dict_b)
...:
In [4]: new_D = D()
In [5]: new_D.__dict__
Out[5]: {
'd': 4, 'a': 1, 'b': 2, 'c': 3}
In [6]: new_D.a
Out[6]: 1
In [7]: new_D.c
Out[7]: 3
In this case , We define two dictionaries outside the class dict_a
and dict_b
, Dictionary key Values are in string format . And we know that the string format is python If not used in eval, It cannot be used directly as a variable name . And by __dict__.update()
After importing the dictionary , Will automatically identify all of them key and value value , Instead, assign a value to the current class as a member variable . But one disadvantage of this method is , Values can only be assigned through a single-layer Dictionary , If you encounter a dictionary with a hierarchy , It will not automatically distinguish the hierarchy for assignment , Like the code below :
In [15]: dict_a = {
'f':{
'h':8},'g':7}
In [16]: new_D = D()
In [17]: new_D.__dict__
Out[17]: {
'd': 4, 'f': {
'h': 8}, 'g': 7, 'c': 3}
According to this special scenario mentioned at the end of the previous chapter , We need to recurse the elements in the dictionary , If you encounter nested dictionary elements , Then recursively add the element to the member variable of the next level , The specific code is as follows :
''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
dict_a = {
'f':{
'h':8},'g':7}
dict_b = {
'c':3}
class D:
def __init__(self, *args):
for arg in args:
for k, v in arg.items():
if isinstance(v, dict):
self.__dict__[k] = D(v)
else:
self.__dict__[k] = v
new_D = D(dict_a, dict_b)
print (new_D.__dict__)
print (new_D.f.h)
The final output is as follows :
{
'f': <__main__.D object at 0x7fd2f32a4340>
, 'g': 7, 'c': 3}
8
You can see , We finally passed new_D.f.h
Methods , Successfully read... From the original nested dictionary value. Although this kind of writing doesn't look very elegant , But there seems to be no better solution . also , Through the practice of this small problem , Found another slightly interesting problem : Yes python When updating dictionary types in , If key With a dot in the string , such as parDict['group1.b'] = 3
, It can only be updated in the form of such a string , If you use parDict.update(group1.b=4)
An error will be reported , This is because the point number is python Is not an identifier in , Cannot be used to name , The original content is as follows :
The valid characters for identifiers are the same as in Python 2.x:
the uppercase and lowercase letters A through Z, the underscore _ and,
except for the first character, the digits 0 through 9.
The problem scenario solved in this paper is as follows : If given a dictionary , For example, generally from json Documents or npz The data loaded in the file is the data structure of the dictionary , If we want to assign this dictionary to a class , And make the dictionary key and value As the member variable name and member variable value of the class respectively , So how to achieve it ?
For a flattened Dictionary ( No nested dictionaries ), We use it directly update You can put all the words in the dictionary key and value Change to the member variable of the current class . What's more troublesome is the hierarchical dictionary with nested dictionaries , At this point, we can only use the loop , And recursively assign values to the member variables of the class .