天天看點

python動态建立類_[Python]利用type()動态建立類

Python作為動态語言,可以動态地建立函數和類定義。比如說定義一個Hello類,就寫一個hello.py子產品:

#! /usr/bin/env python

#coding=utf-8

class Hello(object):

def hello(self,name='world'):

print("Hello,%s"%name)

當Python解釋器載入hello子產品時,會依次執行該子產品的所有語句,執行的結果就是動态建立了一個Hello的class對象:

from hello import Hello

h = Hello()

h.hello()

print( type(Hello))

print (type(h))

Hello,world

可以看到,Hello的class對象是type類型的,即Hello類是type()函數建立的。可以通過type()函數建立出Hello類,而無需class Hello(object)...這樣的定義:

def fn(self,name="world"):

print("Hello,%s"%name)

Hello = type('Hello',(object,),dict(hello=fn))

h = Hello()

h.hello()

print(type(Hello))

print(type(h))

Hello,world

要動态建立一個class對象,type()函數依次傳入3個參數:

1、class的名稱,字元串形式;

2、繼承的父類集合,注意Python支援多重繼承,如果隻有一個父類,注意tuple的單元素寫法;

3、class的方法名稱與函數綁定,這裡我們把函數fn綁定到方法名hello上。