python中getattr函数使用方法 getattr实现工厂模式
返回的是这个方法的对象 就可以直接使用了 如果要添加新的格式 只需要在模块中写入新的方法函数 在调用output函数时使用新的参数就可以使用不同的格式输出
确实很方便
为了加深对getattr函数的理解 转载一篇英文的说明
Python's getattr function is used to fetch an attribute from an object, using a string object instead of an identifier to identify the attribute. In other words, the following two statements are equivalent:
[code]value = obj.attributevalue = getattr(obj, "attribute")If the attribute exists, the corresponding value is returned. If the attribute does not exist, you get an AttributeError exception instead.
The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects.
path = getattr(sys, "path")doc = getattr(len, "__doc__")The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods:
result = obj.method(args)
func = getattr(obj, "method")result = func(args)or, in one line:
result = getattr(obj, "method")(args)Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern:
try: func = getattr(obj, "method")except AttributeError: ... deal with missing method ...else: result = func(args)The function takes an optional default value, which is used if the attribute doesn't exist. The following example only calls the method if it exists:
func = getattr(obj, "method", None)if func: func(args)Here's a variation, which checks that the attribute is indeed a callable object before calling it.
func = getattr(obj, "method", None)if callable(func): func(args)
- 介绍php设计模式中的工厂模式
- asp.net 简单工厂模式和工厂方法模式之论述
- javascript 模式设计之工厂模式详细说明
- 工厂模式在Zend Framework中应用介绍
- PHP高级对象构建 工厂模式的使用
- 基于php设计模式中工厂模式详细介绍
- Python __getattr__与__setattr__使用方法
- java反射机制+工厂模式+配置文件----->在谈到spring配置文件
- python 内建函数setattr() getattr()
- Head First -- 工厂方法
- Head First -- 简单工厂
- Head First -- 抽象工厂模式
- 【论题】+【方案】设计模式和工厂模式
- 工厂方法模式与抽象工厂模式
- Java设计模式 创建模式-工厂模式(Factory)
- C++设计模式(1)-工厂模式
- java面试题
- 工厂方法模式
- 读书笔记系列1:大话设计模式 -- 简单工厂模式
- 工厂模式