反射主要是指程序可以访问、检测和修改它本身状态或行为的一种能力
python面向对象中的反射:通过字符串的形式操作对象相关的属性。
1.getattrhastattrsetattrdelattr
class Foo:
f = '类的静态变量'
def __init__(self,name,age):
self.name=name
self.age=age
def say_hi(self):
print('hi,%s'%self.name)
obj=Foo('egon',73)
#检测是否含有某属性
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))
#获取属性
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()
print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
#设置属性
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))
#删除属性
delattr(obj,'age')
delattr(obj,'show_name')
delattr(obj,'show_name111')#不存在,则报错
print(obj.__dict__
2.将另以py文件导入(与当前操作文件在同一目录下)
#Ss.py
name = 'Sroxi'
def func():
return 123
#反射.py
1.
import Ss
print(Ss.name)
r = Ss.func()
print(r)
2.
import Ss
a = getattr(Ss,'name')
b = getattr(Ss,'func')
c = b()
print(a)
print(c)
3.isinstance和issubclass
isinstance(obj,cls)检查是否obj是否是类 cls 的对象
class Foo(object):
pass
obj = Foo()
isinstance(obj, Foo)
issubclass(sub, super)检查sub类是否是 super 类的派生类
class Foo(object):
pass
class Bar(Foo):
pass
issubclass(Bar, Foo)