• 关于python反射的getattr,我终于想通了!


    其实看了getattr 的解释一直不知道到底该怎么用才好。心想这直接调用就好干嘛这么麻烦
    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.
    
    最近看了drf的源码才明白:
    if request.method.lower() in self.http_method_names:
      handler = getattr(self, request.method.lower(),
      self.http_method_not_allowed)
    else:
      handler = self.http_method_not_allowed
    

    简单来说 getattr就是能吧原先原先对象点属性,或者对象点方法换成对象点任意字符串的操作。正常来说对象点一个字符串肯定会报错的。getattr操作就在这个字符串也可以是一个变量不必须是类里面的方法

    举一个栗子

    例如一个需求要调用一些对象里面的方法,但在有的方法 a对象有b对象没有。
    a对象象封装了另一种功能功能b对象封装了另一种功能 。他们共同完成一件事。现在要能够让请求的时候自动调用该调用对象方法
    一般操作就是 判断对象然后分别调用可以调哟的方法。需要写大量的判段,不然程序无法执行例如这样:
    class A(object):
    def get(self):
    print("执行get方法")
    pass


    class B(object):
    def post(self):
    print("执行post方法")
    pass

    aobj = A()
    bobj = B()

    objlist = [aobj, bobj]

    for obj in objlist: #必然会报错 obj.get() obj.post()

    使用gettattr后:

    class A(object):
    def get(self):
    print("执行get方法")
    pass


    class B(object):
    def post(self):
    print("执行post方法")
    pass

    aobj = A()
    bobj = B()

    objlist = [aobj, bobj]
    for i in objlist:
    funname = 'post'
    handle = getattr(i, funname, None)
    if handle:
    handle()

     getattr(self,Name ,None) 如果没有这些方法就返回None。要是没有这个参数就会触发异常

  • 相关阅读:
    题解 P2812 【校园网络【[USACO]Network of Schools加强版】】
    拓展卢卡斯定理(伪)
    [洛谷P3807] 【模板】卢卡斯定理
    一道使用Fibonnaci数列通项公式的趣味题目
    [洛谷P3292] [SCOI2016]幸运数字
    [洛谷P3812] 【模板】线性基
    [洛谷P3857] [TJOI2008]彩灯
    2019.06.17课件:[洛谷P1310]表达式的值 题解
    常数PK系列汇总
    关于BFS和dijkstra(2019.04.20)
  • 原文地址:https://www.cnblogs.com/lzxcloud/p/12892983.html
Copyright © 2020-2023  润新知