python之type函數


python 的type 函數 的介紹的   下面就是此函數的參數   三個參數的意義

'''
type(class_name, base_class_tuple, attribute_dict)
class_name type創建類的名稱,就是通常定義類的類名
base_class_tuple type創建類所繼承類的元組,通常定義時繼承的父類
attribute_dict type創建類的屬性,不單純指值屬性,也可以是方法
'''

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_method(self): #這里要接受至少一個參數,作為類方法會默認傳入self
    print 'test_method'

class A(object):
    def __init__(self, a):
        print 'call a __init__'
        self.a = a

B = type('B', (A,), {'b':1, 'test_method':test_method})
b1 = B(5)  #因為繼承A類,初始化要提供一個參數給a,不能直接B()建實例
b2 = B(6)
print b1.b, ' | ' , b2.b  #運行結果 1 | 1
b2.b = 10
print b1.b, ' | ' , b2.b  #運行結果 1 | 10
b1.test_method()          #和通常類方法調用沒有區別

運行結果:

call a __init__
call a __init__
1  |  1
1  |  10
test_method

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM