Python中的内置函数【isinstance(object, classinfo)】需要传入两个参数,第一个参数object是一个类的对象,第二个参数classinfo是一个类的类名;其功能是判断object这个对象是不是classinfo这个类的实例或者classinfo这个类子类的实例,如果是的话,将返回True,不是的话将返回False,测试代码如下所示。
# coding=utf-8
# 定义一个父类
class Father():
def __init__(self):
pass
# 定义一个子类
class Children(Father):
def __init__(self):
super(Children, self).__init__()
def main():
father = Father()
child = Children()
if isinstance(father, Father):
print("father is a instance of Father.")
if isinstance(child, Children):
print("child is a instance of Children.")
if isinstance(child, Father):
print("child is a instance of Father.")
if __name__ == '__main__':
main()
输出的结果如下所示。
father is a instance of Father.
child is a instance of Children.
child is a instance of Father.