亲宝软件园·资讯

展开

一文带你了解Python中的type,isinstance和issubclass

勇敢努力拼搏 人气:0

type

type方法有两种重载形式:

使用第一种重载形式的时候,传入一个【object】类型,返回一个【type】对象,通常与object.__class__方法的返回值相同。

使用第二种重载形式的时候,也会得到一个【type】对象,本质上来说这是一种动态类,参数含义如下:

示例

重载形式1

 class A(object):
     pass
 ​
 a = A()
 print(type(a), a.__class__, type(A))
 -----------------------------
 <class '__main__.A'> <class '__main__.A'> <class 'type'>

重载形式2

 class OldClass(object):
     a = 1
 ​
     def __init__(self) -> None:
         self.name = "OldClass"
 ​
     def get_name(self):
         return self.name
 ​
 ​
 my_dynamic_cls = type('DynamicClass', (OldClass,),
                       dict(name='dynamic', a=2, b=3, c=4))
 ​
 new_obj = my_dynamic_cls()
 print(my_dynamic_cls.__dict__)
 print(new_obj.__dict__, type(new_obj))
 -----------------------------
 {'name': 'dynamic', 'a': 2, 'b': 3, 'c': 4, '__module__': '__main__', '__doc__': None}
 {'name': 'OldClass'} <class '__main__.DynamicClass'>

在上面的示例中我们使用type成功创造了一个动态类并添加了几个类属性,由于指定了【OldClass】作为父类,所以动态生成的类也具有【OldClass】的全部特性。

动态生成一个类的时候不光可以指定类属性,还可以绑定类方法,示例如下:

 class OldClass(object):
     a = 1
 ​
     def __init__(self) -> None:
         self.name = "OldClass"
 ​
     def get_name(self):
         return self.name
 ​
 def print_msg(msg: str) -> None:
     print(msg)
 ​
 my_dynamic_cls = type('DynamicClass ', (OldClass,),
                       dict(name='dynamic', a=2, b=3, c=4, method=print_msg))
 ​
 new_obj = my_dynamic_cls()
 my_dynamic_cls.method("使用动态绑定的方法!!")
 print(my_dynamic_cls.__dict__)
 -----------------------------
 使用动态绑定的方法!!
 {'name': 'dynamic', 'a': 2, 'b': 3, 'c': 4, 'method': <function print_msg at 0x00000188189F73A0>, '__module__': '__main__', '__doc__': None}

isinstance

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a union of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised. TypeError may not be raised for an invalid type if an earlier check succeeds.

——PythonDoc

isinstance方法用来检查给定的对象是否是给定类型的实例或者是给定类型的任意子类的实例,通常使用该方法进行对象类型校验。

示例

 class AMetaClass(type):
 ​
     def __new__(cls, *args, **kwargs):
         return type.__new__(cls, *args, **kwargs)
 ​
 ​
 class BMetaClass(AMetaClass):
     pass
 ​
 ​
 class AClass(object, metaclass=BMetaClass):
 ​
     def __init__(self, name: str) -> None:
         self.name = name
 ​
 ​
 class BClass(AClass):
 ​
     def __init__(self, name: str) -> None:
         super().__init__(name)
         
 obj_a = AClass('a')
 obj_b = BClass('b')
 -----------------------------
 print(isinstance(obj_b, AClass)) -> True
 print(isinstance(obj_b, BClass)) -> True
 print(isinstance(obj_b, AMetaClass)) -> False
 print(isinstance(obj_b, BMetaClass)) -> False
 print(isinstance(obj_b, type)) -> False
 print(isinstance(BClass, AMetaClass)) -> True
 print(isinstance(BClass, BMetaClass)) -> True
 print(isinstance(BClass, type)) -> True

总结一下,isinstance方法检查的范围就是参数的模板层按照继承关系进行检索。

issubclass

issubclass(class: type, classinfo: Union[type, ...])方法用来判断指定的两个类型之间的从属关系,如果【class】是【classinfo】的子类返回真(True),否则返回假(False)。

有几点注意事项这里说一下:

示例

 class AMetaClass(type):
 ​
     def __new__(cls, *args, **kwargs):
         return type.__new__(cls, *args, **kwargs)
 ​
 ​
 class BMetaClass(AMetaClass):
     pass
 ​
 ​
 class AClass(object, metaclass=BMetaClass):
 ​
     def __init__(self, name: str) -> None:
         self.name = name
 ​
 ​
 class BClass(AClass):
 ​
     def __init__(self, name: str) -> None:
         super().__init__(name)
         
 obj_a = AClass('a')
 obj_b = BClass('b')
 -----------------------------
 ​
 issubclass(AMetaClass, type) -> True
 issubclass(BMetaClass, type) -> True
 issubclass(BMetaClass, AMetaClass) -> True
 issubclass(AClass, AMetaClass) -> False
 issubclass(AClass, BMetaClass) -> False
 issubclass(BClass, AClass) -> True
 issubclass(AClass, obj_a) -> TypeError: arg 2 must be a class
 issubclass(obj_a, AClass) -> TypeError: arg 1 must be a class

从程序结果可以看到传入元类和类返回永远是假,并且不能直接传入对象。

综合示例

为了更好的让大家明白这三者之间的区别和联系,我画了一张图

这是初始状态,定义了三个对象,三个类和三个元类,它们之间的关系如上图所示;

 class M1(type):
 ​
     def __new__(cls, *args, **kwargs):
         return type.__new__(cls, *args, **kwargs)
 ​
 ​
 class M2(M1):
     pass
 ​
 ​
 class M3(type):
 ​
     def __new__(cls, *args, **kwargs):
         return type.__new__(cls, *args, **kwargs)
 ​
 ​
 class C1(metaclass=M3):
     pass
 ​
 ​
 class C2(C1):
     pass
 ​
 ​
 class C3(metaclass=M2):
     pass
 ​
 ​
 o1 = C1()
 o2 = C2()
 o3 = C3()

isinstance

针对对象

以【O2】为例,它的检索范围如下图红线所示:

针对类

以【C3】为例,它的检索范围如下图红线所示:

issubclass

针对类

以【C2】为例,返回真值的范围如下:

针对元类

以【M2】为例,返回真值的范围如下:

总结

调用type方法

调用isinstance方法

调用issubclass方法

加载全部内容

相关教程
猜你喜欢
用户评论