python - 如何在python中返回时始终强制调用类方法
问题描述
我有一ReportEntry
堂课
class ReportEntry(object):
def __init__(self):
# Many attributes defined here
... # Lot many setattr/getattr here
def validate(self):
# Lot of validation code in here
return self
多个其他类保持has-a
与ReportEntry
类的关系
class A(object):
def test1(self):
t1 = ReportEntry()
# Assign the attribute values to t1
return t1.validate()
def test2(self):
t2 = ReportEntry()
# Assign the attribute values to t2
return t2.validate()
并且有多个这样的类,如 A.
我需要强制每个类ReportEntry
实例调用或之前调用validate()
.return
return
基本上,任何实例ReportEntry
都不应逃脱验证,因为如果缺少某些内容,最终报告生成将失败。
我怎样才能做到这一点?
解决方案
您可以编写一个类装饰器:
import inspect
def validate_entries(cls):
def validator(fnc): # this is a function decorator ...
def wrapper(*args, **kwargs):
rval = fnc(*args, **kwargs)
if isinstance(rval, ReportEntry):
# print('validating')
return rval.validate()
return rval
return wrapper
for name, f in inspect.getmembers(cls, predicate=inspect.isfunction):
setattr(cls, name, validator(f)) # .. that we apply to all functions
return cls
现在您可以定义所有A
类似的类:
@validate_entries
class A(object):
# ...
这将验证任何' 方法ReportEntry
返回的任何内容。A
推荐阅读
- java - 带有哈希密码的登录页面
- twilio - 在对话流中获取用户的位置
- android - 在 React Native 中为 Android 4.X 启用 TLS 1.1/1.2
- tsql - 如何从 cte 更新第二个表以使其可靠工作
- python - RequestsLibrary 支持带有 pabot 的并行执行套件吗?
- r - R在data.table中按组创建递归变量
- javascript - 无法在函数中推送数组
- r - R 绘制生存曲线并计算特定时间的 P 值
- swift - 如何在 SwipeCellKit 中实现左右滑动
- ansible - 使用 ansible 编辑 json 文件