type动态创建类理解

查看python里面type函数,点击进去之后源码:

def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
    """
    type(object_or_name, bases, dict)
    type(object) -> the object's type
    type(name, bases, dict) -> a new type
    # (copied from class doc)
    """
    pass

查看代码的解释:
type(object)返回的是是对象的类型
比如:

a=1                        
b="23"                     
def dd():                  
    print("sss")           
class C:                   
    def way1( self ):      
        return 123         
    def way2( self ):      
        return 234         
print(type(a))             
print(type(b))             
print(type(dd))            
print(type(C))             
运行结果:
C:\Users\18566\AppData\Local\Programs\Python\Python38\python.exe C:/Users/18566/Desktop/APPAutoTest/learn_fenjie/list_tuple_dict_jie.py
<class 'int'>
<class 'str'>
<class 'function'>
<class 'type'>

Process finished with exit code 0

type(name, bases, dict) -> a new type,这种类型的参数则重新生成一个新的类,即动态生成类。
name—表示类名
bases—表示继承的父类,是一个元组类型
dict—字典类型,类的方法、属性等
举例说明:

 class A:
    gender1="nv"
    def functionA( self ):
        return ("hello A!")
def function1(self,a,b):
    self.name=10
    return(a+b)
def function2(self,str1):
    return("function2!!!"+str1)
t=type("function23",(),{"name1":"www","function11":function1,"fun2":function2})
typ=t()
print(t.__name__)
print(typ.name1)
print(typ.function11(3,4))
print(typ.fun2("hahah"))
print(typ.name)
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
t2=type("nihao",(A,),{"name1":"王二小","gender":"男","fu":function1})
print(A.__name__)
typen=t2()
print(typen.__class__)
print(t2.__name__)
print(typen.name1)
print(typen.gender)
print(typen.gender1)
print(typen.functionA())
print(typen.fu(12,23))
运行结果如下:
C:\Users\18566\AppData\Local\Programs\Python\Python38\python.exe C:/Users/18566/Desktop/APPAutoTest/learn_fenjie/list_tuple_dict_jie.py
function23
www
7
function2!!!hahah
10
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
<class '__main__.nihao'>
nihao
王二小
男
nv
hello A!
35

Process finished with exit code 0

从上述运行结果看:type(“x6”,(x5),{“x1”:“x2”,“x3”:x4})解释如下:
x6就是动态生成的类的名字,目前看好像也不能直接引用,没看出来它的作用。
x5是继承的父类,父类的方法和属性,子类都有,和class一样的继承
“x1”:"x2"则是类的属性
“x3”:x4则是x4函数作为类的方法,在类里面的别名是x3
另外要作为类的方法,则要在形参里面加入self,如果方法里面有实列属性则需要加self.x=“xxx”。
****目前没按出来起了类名之后有什么用处,但是不写肯定是不对的,即使动态生成类,类名应该不能和已有的类名相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值