2

A 类型的对象和有没有办法以编程方式包装类对象?

给定

class A(object):
    def __init__(self):
        ## ..

    def f0(self, a):
        ## ...

    def f1(self, a, b):
        ## ..

我想要另一个包装A的类,例如

class B(object):
    def __init__(self):
        self.a = A()

    def f0(self,a):
        try:
            a.f0(a)
        except (Exception),ex:
            ## ...

    def f1(self, a, b):
        try:
            a.f1(a,b)
        except (Exception),ex:
            ## ...

有没有办法通过类的反射/检查来创建B.f0& ?B.f1A

4

3 回答 3

4

如果你想B通过调用预定义类的函数来创建类A,你可以简单地B = wrap_class(A)使用如下所示的函数wrap_class

import copy

def wrap_class(cls):
    'Wraps a class so that exceptions in its methods are caught.'
    # The copy is necessary so that mutable class attributes are not
    # shared between the old class cls and the new class:
    new_cls = copy.deepcopy(cls)
    # vars() is used instead of dir() so that the attributes of base classes
    # are not modified, but one might want to use dir() instead:
    for (attr_name, value) in vars(cls).items():
        if isinstance(value, types.FunctionType):
            setattr(new_cls, attr_name, func_wrapper(value))
    return new_cls

B = wrap_class(A)

正如 Jürgen 所指出的,这会创建一个类的副本;但是,如果您真的想保留原始课程A(如原始问题中建议的那样),则仅需要这样做。如果你不关心A,你可以简单地用一个不执行任何复制的包装器来装饰它,如下所示:

def wrap_class(cls):
    'Wraps a class so that exceptions in its methods are caught.'
    # vars() is used instead of dir() so that the attributes of base classes
    # are not modified, but one might want to use dir() instead:
    for (attr_name, value) in vars(cls).items():
        if isinstance(value, types.FunctionType):
            setattr(cls, attr_name, func_wrapper(value))
    return cls

@wrap_class
class A(object):
    …  # Original A class, with methods that are not wrapped with exception catching

装饰类A捕获异常。

元类版本比较重,但原理类似:

import types

def func_wrapper(f):

    'Returns a version of function f that prints an error message if an exception is raised.'

    def wrapped_f(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception, ex:
            print "Function", f, "raised", ex

    return wrapped_f

class ExceptionCatcher(type):

    'Metaclass that wraps methods with func_wrapper().'

    def __new__(meta, cname, bases, cdict):
        # cdict contains the attributes of class cname:
        for (attr_name, value) in cdict.items():
            if isinstance(value, types.FunctionType):  # Various attribute types can be wrapped differently
                cdict[attr_name] = func_wrapper(value)
        return super(meta, ExceptionCatcher).__new__(meta, cname, bases, cdict)

class B(object):

    __metaclass__ = ExceptionCatcher  # ExceptionCatcher will be used for creating class A

    class_attr = 42  # Will not be wrapped

    def __init__(self):
        pass

    def f0(self, a):
        return a*10

    def f1(self, a, b):
        1/0  # Raises a division by zero exception!

# Test:
b = B()
print b.f0(3.14)
print b.class_attr
print b.f1(2, 3)

这打印:

31.4
42
Function <function f1 at 0x107812d70> raised integer division or modulo by zero
None

实际上,您想要做的通常是由元类完成,该类的实例是一个类:这是一种B基于其解析的 Python 代码(A问题中的 class 代码)动态构建类的方法。有关这方面的更多信息,请参阅 Chris 的 Wiki 中给出的元类的简短描述(第 1 部分和第2-4 部分)。

于 2011-09-28T20:49:24.940 回答
2

元类是一种选择,但通常很难理解。如果在简单情况下不需要太多反射,因为很容易捕获太多(内部)函数。如果包装的函数是一个稳定的已知集合,并且 B 可能会获得其他函数,则您可以逐个函数显式委托,并且仍然将错误处理代码保留在一个位置:

class B(object):

    def __init__(self):
        a = A()
        self.f0 = errorHandler(a.f0)  
        self.f1 = errorHandler(a.f1)

如果任务很多,您可以使用 getattr/setattr 在循环中进行分配。

errorhandler 函数将需要返回一个用错误处理代码包装其参数的函数。

def errorHandler(f):
    def wrapped(*args, **kw):
        try:
            return f(*args, **kw)
        except:
            # log or something
    return wrapped

您还可以在未委托给 A 实例的新函数上使用 errorhandler 作为装饰器。

def B(A):
    ...
    @errorHandler
    def f_new(self):
        ...

该解决方案使 B 保持简单,并且非常明确地发生了什么事。

于 2011-09-28T21:01:10.507 回答
0

你可以试试老派__getattr__

class B(object):
  def __init__(self):
    self.a = A()
  def __getattr__(self, name):
    a_method = getattr(a, name, None)
    if not callable(a_method):
      raise AttributeError("Unknown attribute %r" % name)
    def wrapper(*args, **kwargs):
      try:
        return a_method(*args, **kwargs)
      except Exception, ex:
        # ...
    return wrapper

或更新B的字典:

class B(object):
  def __init__(self):
    a = A()
    for attr_name in dir(a):
      attr = getattr(a, attr_name)
      if callable(attr):
        def wrapper(*args, **kwargs):
          try:
            return attr(*args, **kwargs)
          except Exception, ex:
            # ...
        setattr(self, attr_name, wrapper) # or try self.__dict__[x] = y
于 2011-09-28T20:50:24.137 回答