类继承时的setattr奇怪行为

时间:2019-03-27 09:14:46

标签: python python-3.x

在与类和装饰器继承使用setattr时遇到问题。

#!/usr/bin/env python3

import inspect

def make_class_decorator(function_decorator):
  def class_decorator(cls):
    for attr_name in inspect.getmembers(cls, inspect.isroutine):
      attr_name = attr_name[0]
      if str(attr_name).startswith('__') and str(attr_name).endswith('__'): continue
      attr_value = getattr(cls, str(attr_name))
      setattr(cls, attr_name, function_decorator(cls, attr_value))

    return cls
  return class_decorator

@make_class_decorator
def auto_debug_logging(cls, called_function):
  def wrapped(*args, **kwargs):
    print('wrapped')
    return called_function(*args, **kwargs)

  wrapped.__name__ = called_function.__name__
  return wrapped

def xclassmethod(called_function):
  def wrapped(*args, **kwargs):
    print('wrappedx: ' + called_function.__name__)
    return builtins.classmethod(called_function(*args, **kwargs))

  return wrapped

class X:
  @xclassmethod
  def get_i(cls):
    cls._inst = cls()
    return cls._inst

@auto_debug_logging
class A(X):
  pass

@auto_debug_logging
class B(A):
  def test(self):
    print('test')

B.get_i().test()

示例代码显示所有函数都被包装,并在实际调用之前打印“包装”。但是,当我调用B.get_i()。test时,出现以下错误: AttributeError:“ A”对象没有属性“ test”

setattr似乎以某种方式将原始B类设置为A,就像我注释掉问题消失时一样。

0 个答案:

没有答案