On Wed, Feb 4, 2009 at 8:27 AM, spir <denis.s...@free.fr> wrote: > Hello, > > I have a strange problem and cannot see a clear method to solve it. > I would like to build a custom type that is able to add some informational > attributes and a bunch attribute to a main "value". The outline is then: > > class Custom(X): > def __init__(self, value, more): > X.__init__(self) > <define info attributes> > <custom methods> > > The base class is here to inherit value's behaviour and to avoid writing > obj.value all the time. For this type will be heavily used by client code. > The point is, this value may actually be of several builtin types. Logically, > X is value.__class__. I imagine there are solutions using a factory, or > __new__, or maybe metaclass (never done yet)? I cannot find a working method > myself.
If I understand correctly, you have two problems: - creating a class with a dynamic base type - creating a subclass of a built-in value type such as int The first is easily solved with a factory method to create the classes: def make_value_class(base_): class Derived(base_): # etc return Derived IntValue = make_value_class(int) Subclassing builtin types is tricky because the value has to be assigned in the __new__() method, not in __init__(). See for example http://www.python.org/download/releases/2.2.3/descrintro/#__new__ or search the tutor archives for __new__. Note that subclasses of builtin types are not as useful as you might hope because they are not preserved by binary operations. For example given a working IntValue class, if you did x = IntValue(3) y = IntValue(5) z = x+y type(z) is int, not IntValue, so all the special sauce is lost. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor