首页 > 编程 > Python > 正文

Python使用type关键字创建类步骤详解

2019-11-25 12:15:07
字体:
来源:转载
供稿:网友

Python使用type关键字创建类

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

python

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

class Coo:  passobj1 = Coo()print (obj1)c = Cooobj2 = 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创建带静态方法,命令如下:

@staticmethoddef staticm():  print ('staticm')Test5 = type('Test5',(Test,),{'echo':echo,'staticm':staticm})t = Test5()t.staticm()

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

@classmethoddef classm(cls):  print (cls.hi)Test6 = type('Test6',(Test,),{'echo':echo,'staticm':staticm,'classm':classm})Test6.classm()

以上就是相关Python如何使用type关键字创建类的全部内容,感谢大家对武林网的支持。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表