一、isinstance(obj,cls)和issubclass(sub,super)
1.1、isinstance(obj,cls)
isinstance(obj,cls)检查是否obj是否是类 cls 的对象
class Foo(object): pass obj = Foo() print(isinstance(obj,Foo)) #True
1.2、issubclass(sub, super)
issubclass(sub, super)检查sub类是否是 super 类的派生类
class Foo(object): pass class Bar(Foo): pass print(issubclass(Bar,Foo)) #True
二、反射
四个可以实现自省的函数,适用于类和对象(一切皆对象,类本身也是一个对象)
2.1、hasattr(object,name)
判断object中有没有一个name字符串对应的方法或属性
2.2、getattr(object, name, default=None)
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass getattr(object, name, default=None)
2.3、setattr(x, y, v)
设置属性
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass setattr(x, y, v)
2.4、delattr(x, y)
删除属性
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass delattr(x, y)
2.5、示例
1)示例一
class BlackMedium: feature = "Ugly" def __init__(self,name,addr): self.name = name self.addr = addr def sell_house(self): print("%s 黑中介卖房子啦" %self.name) def rent_house(self): print("%s 黑中介租房子啦" %self.name) b1 = BlackMedium("万成置地","天露园") #检测是否含有某属性 print(hasattr(b1,"name")) #True print(hasattr(b1,"sell_house")) #以字符串的形式,否则NameError: name 'sell_house' is not defined #print(hasattr(b1,rent_house)) #NameError: name 'sell_house' is not defined #获取属性 print(getattr(b1,"name")) #万成置地 ==>获取数据属性 func = getattr(b1,"rent_house") #获取函数属性 func() #万成置地 黑中介租房子啦 # getattr(b1,"abc") #当属性不存在时报错AttributeError: 'BlackMedium' object has no attribute 'abc' print(getattr(b1,"abc","不存在")) #不存在 ==>当使用getattr获取属性时,当属性不存在,可以指定默认返回值 #设置属性 setattr(b1,"sb","True") #设置数据属性 print(b1.__dict__) #{'name': '万成置地', 'addr': '天露园', 'sb': 'True'} setattr(b1,"show_name",lambda self:self.name+"_sb") #设置函数属性 print(b1.__dict__) #{'sb': 'True', 'name': '万成置地', 'show_name': <function <lambda> at 0x000001B354757F28>, 'addr': '天露园'} print(b1.show_name(b1)) #万成置地_sb #删除属性 print(b1.__dict__) #{'name': '万成置地', 'sb': 'True', 'addr': '天露园', 'show_name': <function <lambda> at 0x0000029A9F8D7F28>} delattr(b1,"addr") delattr(b1,"show_name") # delattr(b1,"show_name123") #AttributeError: show_name123 属性不存在时报错 print(b1.__dict__) #{'sb': 'True', 'name': '万成置地'}
2)示例二
class Foo(object): staticField = "oldboy" def __init__(self): self.name = name def func(self): return "func" @staticmethod def bar(): return "bar" print(getattr(Foo,"staticField")) #oldboy print(getattr(Foo,"func")) #<function Foo.func at 0x00000237B782E378> print(getattr(Foo,"bar")) #<function Foo.bar at 0x00000228D871E400>
3)示例三
查看自身模块
import sys def s1(): print("s1") def s2(): print("s2") this_module = sys.modules[__name__] print(this_module) #<module '__main__' from 'G:/python/反射.py'> ==> __main__表示当前模块 print(hasattr(this_module,"s1")) #True print(getattr(this_module,"s2")) #<function s2 at 0x000001B74743E378>
4)示例四
导入其他模块,利用反射查看该模块是否存在某个方法
module_test.py:
def test(): print('from the test')
index.py:
import aaa.module_test as obj obj.test() #from the test print(obj) #<module 'aaa.module_test' from 'G:\\python\\aaa\\module_test.py'> print(hasattr(obj,'test')) #True print(getattr(obj,"test")) #<function test at 0x0000024770C3E400>返回函数地址 getattr(obj,'test')() #from the test