zoukankan      html  css  js  c++  java
  • 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))

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

  • 相关阅读:
    慈不掌兵,义不行贾,烂好人难成大业!
    克服焦虑
    静态路由汇总(路由聚合)
    OSPF协议介绍及配置 (下)
    OSPF协议介绍及配置 (上)
    我为什么鼓励工程师写blog
    佛弟子有三样东西需要永远保密
    【交换机在江湖】第十三章 VLAN划分篇
    FileZilla Server ftp 服务器下通过alias别名设置虚拟目录(多个分区)
    Java 对象和类
  • 原文地址:https://www.cnblogs.com/yaoqingzhuan/p/10633279.html
Copyright © 2011-2022 走看看