Home > other >  Python class variable assignment problem
Python class variable assignment problem

Time:09-30

One of my classes, have more than one variable
The class Person (object) :
Def __init__ (self) :
The self. The name=None
The self. The age=None
The self. The address=None

When I get a list
{" name ":" zhang ", "age" : 22}
I am going to put all the elements in the list assigned to the class, because of some variables are not, so I want to traverse the list ways, but the cycle time don't know how to convey the key to dynamically, and then give the corresponding class variable assignment

CodePudding user response:

Call Magic Methods __dict__ directly to the dictionary data is assigned to it

CodePudding user response:

The original poster is like this?

 
The class Person (object) :
Def __init__ (self, mydict) :
The self. The name=None
The self. The age=None
The self. The address=None
Self. __dict__. Update last line (mydict) # must put

Def __repr__ (self) :
Return the STR (self. __dict__)

If __name__=="__main__ ':
Mydict={" name ":" zhang ", "age" : 22}
P=Person (mydict)
Print (p)

CodePudding user response:

Two small problems deserve improvement:

1. The class Person (object) : write the class Person () : can, because when define the class is inherited by default object!
2. Type a list of actual data clearly is a dictionary (but not the list type), so the variable name list should be changed to a more intuitive, such as mydict!
  • Related