面向对象--反射

--反射

可以用过字符串的形式来操作(增删改查)一个对象的属性

有几种方法

  getattr()获取

  hasattr()判断

  setattr()赋值

  delattr()删除

 

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person("alex",22)
if hasattr(p,"name2"):      #hasattr()判断对象P中是否存在name2的属性
    print("存在name2")
else:
    print('不存在name2')

print(getattr(p,"age"))
setattr(p,"sex","male")
print(p.sex)

 

应用场景:

在django的框架中的cbv的视图中的dispatch()方法,就是用反射来判断http请求的类型

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        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
        return handler(request, *args, **kwargs)

 

posted @ 2022-11-14 23:17  powfu  阅读(16)  评论(0)    收藏  举报