Python基于内置函数type创建新类型
英文文档:
classtype(object)
classtype(name,bases,dict)
Withoneargument,returnthetypeofanobject.Thereturnvalueisatypeobjectandgenerallythesameobjectasreturnedbyobject.__class__.
Theisinstance()built-infunctionisrecommendedfortestingthetypeofanobject,becauseittakessubclassesintoaccount.
Withthreearguments,returnanewtypeobject.Thisisessentiallyadynamicformoftheclassstatement.Thenamestringistheclassnameandbecomesthe__name__attribute;thebasestupleitemizesthebaseclassesandbecomesthe__bases__attribute;andthedictdictionaryisthenamespacecontainingdefinitionsforclassbodyandiscopiedtoastandarddictionarytobecomethe__dict__attribute.
返回对象的类型,或者根据传入的参数创建一个新的类型
说明:
1.函数只传入一个参数时,返回参数对象的类型。返回值是一个类型对象,通常与对象.__class__返回的对象相同。
#定义类型A >>>classA: name='definedinA' #创建类型A实例a >>>a=A() #a.__class__属性 >>>a.__class__#type(a)返回a的类型 >>>type(a) #测试类型 >>>type(a)==A True
2.虽然可以通过type函数来检测一个对象是否是某个类型的实例,但是更推荐使用isinstance函数,因为isinstance函数考虑了父类子类间继承关系。
#定义类型B,继承A >>>classB(A): age=2 #创建类型B的实例b >>>b=B() #使用type函数测试b是否是类型A,返回False >>>type(b)==A False #使用isinstance函数测试b是否类型A,返回True >>>isinstance(b,A) True
3.函数另一种使用方式是传入3个参数,函数将使用3个参数来创建一个新的类型。其中第一个参数name将用作新的类型的类名称,即类型的__name__属性;第二个参数是一个元组类型,其元素的类型均为类类型,将用作新创建类型的基类,即类型的__bases__属性;第三个参数dict是一个字典,包含了新创建类的主体定义,即其值将复制到类型的__dict__属性中。
#定义类型A,含有属性InfoA >>>classA(object): InfoA='somethingdefinedinA' #定义类型B,含有属性InfoB >>>classB(object): InfoB='somethingdefinedinB' #定义类型C,含有属性InfoC >>>classC(A,B): InfoC='somethingdefinedinC' #使用type函数创建类型D,含有属性InfoD >>>D=type('D',(A,B),dict(InfoD='somethingdefinedinD')) #C、D的类型 >>>C>>>D #分别创建类型C、类型D的实例 >>>c=C() >>>d=D() #分别输出实例c、实例b的属性 >>>(c.InfoA,c.InfoB,c.InfoC) ('somethingdefinedinA','somethingdefinedinB','somethingdefinedinC') >>>(d.InfoA,d.InfoB,d.InfoD) ('somethingdefinedinA','somethingdefinedinB','somethingdefinedinD')
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。