Python使用type关键字创建类

打开命令行窗口,输入python,进入python交互环境

python

一般创建类使用class关键字即可,测试命令如下:

class Coo:

  pass

obj1 = Coo()

print (obj1)

c = Coo

obj2 = c()

print (obj2)

type关键字可以动态的创建类,接收参数(类名,父类元组,属性的字典),如创建一个类,没有父类,没有属性,命令如下:

Test = type('Test',(),{})

print (Test)

t = Test()

print (t)

接收type函数返回的变量可以是任意命令,传入type的才是类名,变量只是类的引用

使用type创建有属性的类,命令如下:

Test = type('Test2',(),{'hi':True})

print (Test)

print (Test.hi)

t = Test()

print (t.hi)

使用type创建并继承的类

Test3 = type('Test3',(Test,),{})

t = Test3()

print (t.hi)

使用type创建带实例方法的类,命令如下:

def echo(self):

  print (self.hi)

Test4 = type('Test4',(Test,),{'echo':echo})

hasattr(Test,'echo')

hasattr(Test4,'echo')

使用type创建带静态方法,命令如下:

@staticmethod

def staticm():

  print ('staticm')

Test5 = type('Test5',(Test,),{'echo':echo,'staticm':staticm})

t = Test5()

t.staticm()

使用type创建带类方法的类,命令如下:

@classmethod

def classm(cls):

  print (cls.hi)

Test6 = type('Test6',(Test,),{'echo':echo,'staticm':staticm,'classm':classm})

Test6.classm()