This is a very old post, but introspection is not a way to solve this problem, because it is easier to solve with metaclass and a little clever logic for constructing classes using descriptors .
import types
The key to doing this work is the metaclass - it searches for the attributes defined in the classes that it creates to find foobar
descriptors. As soon as this happens, he passes them information about the classes in which they participate, using the init_self
and init_cls
descriptor methods.
init_self
is called only for the class on which the handle is defined. Changes must be made to foobar
, because the method is called only once. For now, init_cls
is called for all classes that have access to the decorated method. References to foobar
classes can be made here.
import inspect class MetaX(type): def __init__(cls, name, bases, classdict): # The classdict contains all the attributes # defined on **this** class - no attribute in # the classdict is inherited from a parent. for k, v in classdict.items(): if isinstance(v, foobar): v.init_self(k, cls) # getmembers retrieves all attributes # including those inherited from parents for k, v in inspect.getmembers(cls): if isinstance(v, foobar): v.init_cls(cls)
Example
# for compatibility import six class X(six.with_metaclass(MetaX, object)): def __init__(self): self.value = 1 @foobar def f(self, x): return self.value + x**2 class Y(X): pass
rmorshea May 26 '16 at 3:53 a.m. 2016-05-26 03:53
source share