Python的内置函数getattr
1
getattr(object, name[, default])

文档

返回对象命名属性的值。name必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如, getattr(x, 'foobar') 等同于 x.foobar。如果指定的属性不存在,且提供了 default 值,则返回它,否则触发 AttributeError

Help

1
2
3
4
5
6
7
8
9
In [5]: help(getattr)                                                   Help on built-in function getattr in module builtins:

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.

In [6]: getattr(str, "join") Out[6]: <method 'join' of 'str' objects>

应用

Django CBV模式

1
2
OneView.as_view()
getattr(request.method.lower)

多个请求封装在一个类中, 通过getattr()获得匹配方法

文章作者: Shoor
文章链接: https://shoorday.github.io/posts/4c00b674/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Shoor's Blog