什么是反射?
- 在运行时获取对象的类型,属性,和类当中的成员信息.等信息称之为反射,也叫自省. 简单点说可以那镜子来比喻反射,通过反射就可以检测修改本身
python反射操作的方法
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
print(getattr(Point(1,2), "x"))
print(Point(1,2).x)
print(getattr(Point(1,2), "z"))
print(Point(1,2).z)
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1,2)
setattr(p, "x", 10)
print(getattr(p, "x"))
setattr(p, "z", 11)
print(getattr(p, "z"))
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, __o):
return Point(self.x + __o.x,self.y + __o.y)
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, __o):
return Point(self.x + __o.x,self.y + __o.y)
p = Point(1,2)
print(hasattr(p, "add"))
print(hasattr(p, "sub"))
小案例
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def show(self):
return "<Point {},{}>".format(self.x, self.y)
def add(self, __o):
return Point(self.x + __o.x, self.y + __o.y)
__repr__ = show
p1 = Point(1, 2)
p2 = Point(0, 4)
if not hasattr(Point, "__add__"):
setattr(Point, "__add__", lambda self, other:Point(self.x + other.x, self.y + other.y))
p3 = p1 + p2
if not hasattr(p1, "sub"):
setattr(p1, "sub", lambda self, other:Point(self.x - other.x, self.y - other.y))
print(p1.sub(p2))