An interesting usage of the Python built-in function Type ()

Source: Internet
Author: User
This article mainly introduces an interesting usage of the Python built-in function Type (). This article describes an interesting usage that I personally found. Note that this writing method will make the code hard to read, you can refer to a piece of code of type on the Internet today and check the document to see how to use the three parameters of type.

Http://docs.python.org/2/library/functions.html#type

Previously, we only knew that type can detect object types. Then I found an interesting usage.

The code is as follows:


Def println (self ):
A = 1 + 1

Print "% s, % s" % (self. aa,)

A = type ('A', (), {'a': 'Print A', 'println': println })

A = ()

Type ()
Out [11]: _ main _.

A. println ()
Print a, 2


The first parameter is the class name, the second tuple is the parent class, and the third is the attribute.

Haha, I think it's funny. although the first parameter in My function is self, if I write a piece of code, I use this method to define the class, and then I don't pay attention to the class name specification, the code will become very difficult to read.

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.