摘要:
下文讲述Python中判断实例化对象是否由指定类生成的方法分享,如下所示:
实现思路:
使用isinstance()方法即可判断一个实例对象是否由指定类生成
isinstance()方法的语法:
isinstance(obj,Class)
-------参数说明------
obj:实例化对象
Class:指定类
-------返回值说明----
返回True代表由指定类生成
例:
Python 实例化对象由指定类生成示例分享
#maomao365.com
#isinstance方法的示例分享
class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print ("我是父类构造函数")
def parentMethod(self):
print ('我是父类方法')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print ("父类属性 :", Parent.parentAttr)
class Child(Parent): # 定义子类
def __init__(self):
print ("我是子类构造方法")
def childMethod(self):
print ('我是子类方法')
t1 = Parent();
t2 = Child();
print(isinstance(t2,Child)); #输出True
print(isinstance(t2,Parent)); #输出True