Python implements struct class instances using the decorator and metaprogramming. python instances
There is a convenient Struct class in Ruby to implement Struct. In this way, you do not have to define a complete class as an access attribute.
Copy codeThe Code is as follows:
Class Dog <Struct. new (: name,: age)
End
Fred = Dog. new ("fred", 5)
Printf "name: % s age: % d", fred. name, fred. age
# Name: fred age: 5
This can also be done in Python3.4, but it is cumbersome to write. This includes the annoying way of writing self. name = name.
Copy codeThe Code is as follows:
Class Dog (object ):
Def _ init _ (self, name, age ):
Self. name = name
Self. age = age
Fred = Dog ("fred", 5)
Print ('name: {name} age: {age} '. format (name = fred. name, age = fred. age ))
# Name: fred age: 5
I think that Python is omnipotent. Is there a way to simplify the definition of struct attributes? The answer is yes. After learning some Python black magic technologies, I thought of using the decorator functions and metadata programming technology.
Copy codeThe Code is as follows:
Def struct (* name ):
"Decorator Function
Purpose: used to automatically set self. value = value in the class definition.
"""
Def decorator (func ):
Def wrapper (* args, ** kw ):
For I in range (len (name )):
Setattr (args [0], name [I], args [I + 1])
Return func (* args, ** kw)
Return wrapper
Return decorator
Class Dog (object ):
@ Struct ('name', 'age') # Black magic!
Def _ init _ (self, * all_value ):
Pass
Fred = Dog ("fred", 5)
Print ('name: {name} age: {age} '. format (name = fred. name, age = fred. age ))
# Name: fred age: 5
Note that this write method may cause the code structure to be unclear.