python反射
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python反射,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2494字,纯文字阅读大概需要4分钟。
内容图文
![python反射](/upload/InfoBanner/zyjiaocheng/644/314014362719411bba4b2f38575039cb.jpg)
Python中的反射
?反射定义:
Python 中所谓的反射是指通过某个对象的方法或者属性字符串名称来调用该对象的方法或者属性
反射函数:
在Python中反射相关的函数有四个:
1、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
从对象中获取属性或者方法,没有默认值时,如何属性或者方法不存在,则会抛出exception
2、 setattr(obj, name, value)
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to x.y = v
给对象设置属性或者方法,属性值或方法的值为 value
3、 hasattr(obj, name)
Return whether the object has an attribute with the given name
判断对象中是否有name属性或者方法
4、delattr(obj, name)
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to del x.y
删除对象属性或方法
# module.py name = "name" def get(): print("get") import module # 获取模块module中的 get 方法 get = getattr(module,"get") # 执行get方法 get() # 获取模块module中的 name 方法 name = getattr(module,"name") print(name) # 定义一个set函数 def set(): print(" 新增的set方法 ") # 给 module 模块动态新增set方法 setattr(module,"set",set) # 调用 module 中的set方法 module.set() # 输出 新增的set方法 # module 中是否有 get 属性或方法 print(hasattr(module,"get")) # True print(hasattr(module,"name")) # True print(hasattr(module,"aa")) # False # 删除 module 中的 get 方法 delattr(module,"get") # 调用 module 中的 get 方法 getattr(module,"get") # AttributeError: module 'module' has no attribute 'get' # getattr没有默认值,报错
实际应用:
某项目中,实现了计算圆、矩形、三角形的面积的类 Circle、Rect、Triangle,在这三个类中都定义了计算面积的方法,但是方法名称不同
为了方便使用,需要对外提供一个统一的接口
代码实现如下:
class Circle(object): def __init__(self,r): self.r = r def circle_area(self): return self.r**2*3.14 class Rect(object): def __init__(self, w, h): self.w = w self.h = h def rect_area(self): return self.w * self.h class Triangle(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def triangle_area(self): a, b, c = self.a, self.b, self.c p = (a + b + c) / 2 return (p(p - a)(p - b)(p - c)) ** 0.5 # 对外提供的统一方法 def get_area(obj): for i in ["circle_area", "rect_area", "triangle_area"]: func = getattr(obj, i, None) # 使用反射的方式获取对象中计算面积的方法 if func is not None: return func() c = Circle(4) r = Rect(4,5) # 调用 print(get_area(c)) print(get_area(r))
内容总结
以上是互联网集市为您收集整理的python反射全部内容,希望文章能够帮你解决python反射所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。