isinstance和issubclass
A, isinstance and type
isinstance role: determine first parameter is not the second object parameters, return True else False
In the game project, we will pass over in the end each interface for customer parameter type, if the authentication fails, returned to the client "parameter error" error code.
This is not only easy to debug, and increased robustness. Because the client is cheating, do not easily believe parameter pass over the client.
Type function with authentication type, very easy to use, such as
print(type('foo') == str)
True
print(type(2.3) in (int, float))
True
Now that you have type () to determine the type, why are isinstance () do?
A significant difference in the subclass determination.
type () does not think that is a subclass of parent class type; isinstance () will be considered sub-class is a parent class type.
class Foo(object):
pass
class Bar(Foo):
pass
# type(Foo()) 类型就是自己所在的类名
print(type(Foo()) == Foo)
print(type(Bar()) == Foo)
True
False
# isinstance参数为对象和类
# isinstance()会认为子类是一种父类类型。
print(isinstance(Bar(),Foo))
print(isinstance(Bar(),Bar))
True
True
- It should be noted that the old class with the new class type () result is not the same. Legacy classes are <type 'instance'>.
二 、issubclass
effect:
Analyzing issubclass not a class is a subclass of the second class, is the return True or False
class Parent:
pass
class Sub(Parent):
pass
# 判断第一个参数是不是第二个参数的对象,是返回True否则返回False
print(issubclass(Sub, Parent))
print(issubclass(Parent, object))
True
True