首页 > 解决方案 > 如何在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-aReportEntry类的关系

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().returnreturn

基本上,任何实例ReportEntry都不应逃脱验证,因为如果缺少某些内容,最终报告生成将失败。

我怎样才能做到这一点?

标签: python

解决方案


您可以编写一个类装饰器:

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


推荐阅读