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

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

  • 相关阅读:
    ADO.NET Entity Framework(5)esql (二)。
    google首页动态图片代码
    ms sql 聚合事例
    GridView 一些操作
    《狼与狗的故事》
    Asp.net日期字符串格式化显示方法
    解决网爬工具爬取页面信息出现乱码的问题
    esql的查询结果集 ObjectQuery
    去空空格 null sql
    不安装 oracle的客户,就可以使用pl/sql访问远程oracle 数据库的方法
  • 原文地址:https://www.cnblogs.com/yaoqingzhuan/p/10633279.html
Copyright © 2011-2022 走看看