Python implements struct class instances using the decorator and metaprogramming. python instances

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.