Python内置函数Type()函数一个有趣的用法

WBOY
Release: 2016-06-06 11:22:10
Original
1402 people have browsed it

今天在网上看到type的一段代码 ,然后查了一下文档,才知道type还有三个参数的用法。

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

以前只是知道type可以检测对象类型。然后发现了一个有趣的用法。

代码如下:


def println(self):
a = 1 + 1

print “%s,%s” % (self.aa, a)

A = type(‘A',(),{‘aa':'print a', ‘println': println})

a = A()

type(a)
Out[11]: __main__.A

a.println()
print a,2


第一个参数是类的名字,第二个元组是父类,第三个是属性。

哈哈,我觉得很好笑,虽然我函数里边第一个参数还是写的self,但是如果写一段代码都用这种方法定义类,然后再不注意类名的规范,代码会变的很难读。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!