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))

更多内容请关注微信公众号

 

转载于:https://www.cnblogs.com/yaoqingzhuan/p/10633279.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值