python_0004_type_model builtins.type 解析

发布时间 2023-12-14 17:08:47作者: bioamin

内置函数​type()​有两种语法,分别是:

type(object)
#或者
type(name, bases, dict, **kwds)

 

用法一、用于验证 对象的类型,等价于调用  __class__ 属性

class Animal():
    name=""
    def __init__(self,name):
        self.name = name
    def eat(self):
        return "eat"
    def breath(self):
        return "breath"

def type_test():
    a=Animal("大象")
    print(a.name)    #大象
    print(type(a))       #<class '__main__.Animal'>
    print(a.__class__)   #<class '__main__.Animal'>
    print(type(Animal))  #<class 'type'>

 

用法二、用于构造元类,通过继承现有的 Animal类,构建一个新的类dog

 

    name=""
    def __init__(self,name):
        self.name = name
    def eat(self):
        return "eat"
    def breath(self):
        return "breath"

def type_test():
    a=Animal("大象")
    print(a.name)
    print(type(a))       #<class 'int'>
    print(a.__class__)   #<class 'int'>
    print(type(Animal))  #<class 'type'>



def type_test2():
    #通过type 创建类
    dog=type("dog",(Animal,),{"leg_amt":4})
    #通过type添加的属性是类属性,并不是实例属性
    #通过type可以给类添加普通方法,静态方法,类方法,效果跟class一样
#构建一个新类f
dog_jm=dog("金毛") print(dog.__name__) #dog print(dog.__class__) #<class 'type'> print(dog_jm.name) # 金毛 print(type(dog)) # <class 'type'> print(type(dog_jm)) #<class '__main__.dog'> def is_not_empty(param): ''' 判断变量否为空 ''' return type(param) != type(None) if __name__ == "__main__": type_test2()