Python使用type关键字创建类

2025-10-31 23:56:15

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

python

Python使用type关键字创建类

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

class Coo:

    pass

obj1 = Coo()

print (obj1)

c = Coo

obj2 = c()

print (obj2)

Python使用type关键字创建类

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

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

print (Test)

t = Test()

print (t)

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

Python使用type关键字创建类

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

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

print (Test)

print (Test.hi)

t = Test()

print (t.hi)

Python使用type关键字创建类

5、使用type创建并继承的类

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

t = Test3()

print (t.hi)

Python使用type关键字创建类

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

def echo(self):

    print (self.hi)

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

hasattr(Test,'echo')

hasattr(Test4,'echo')

Python使用type关键字创建类

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

@staticmethod

def staticm():

   print ('staticm')

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

t = Test5()

t.staticm()

Python使用type关键字创建类

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

@classmethod

def classm(cls):

    print (cls.hi)

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

Test6.classm()

Python使用type关键字创建类

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢