zoukankan      html  css  js  c++  java
  • 关于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。要是没有这个参数就会触发异常

  • 相关阅读:
    python+requests+excel 接口测试
    Pycharm配置git
    ubuntu16.04+ROS安装kinectV1
    ubuntu16.04安装有道词典
    ROS kinetic语音识别
    在Ubuntu16.04中python环境下实现tab键补全
    ros kinetic安装rbx1
    ubuntu14.04安装opencv3.1
    ubuntu16.04SSH无法连接
    VC6中函数点go to definition报告the symbol XXX is undefined
  • 原文地址:https://www.cnblogs.com/lzxcloud/p/12892983.html
Copyright © 2011-2022 走看看