Question about accessing class-attributes.

Alex Martelli aleax at aleax.it
Wed Apr 30 18:47:43 EDT 2003


Michele Simionato wrote:
   ...
> class B(object): pass
> class C(B): pass
> c=C()
> super(C,c).__thisclass__() #=> C
> super(C,c).__self_class__() #=> C
> 
> I would like to have an additional attribute (not a method)
> returning the superclass of C, in this case B:

*blink* and if "class D(E, F, G, H, I):", what would "the
superclass" *BE*?

Is what you're looking for something like you could obtain
by, e.g.:

class metasc(type):
    def __new__(meta, name, bases, clasdict):
        if bases: clasdict['__superclass__'] = bases[0]
        else: clasdict['__superclass__'] = None
        return type.__new__(meta, name, bases, clasdict)

???  If so, I fail to see the usefulness.  Otherwise,
could you please explain better?


> Certainly the documentation in
> http://www.python.org/dev/doc/devel/lib/built-in-funcs.html
> 
> has to be changed. It says:
> 
> """
>  super(type[object-or-type])
> 
>       Return the superclass of type. If the second argument is omitted
> the super object returned is unbound. If the second argument is an
> object, isinstance(obj, type) must be true. If the second argument is
> a type, issubclass(type2, type)
> must be true. """
> 
> But it DOES not return the superclass! I admit I myself at the
> beginning was confused.

The documentation is surely imperfect (e.g. by making no reference to
the mro, which is crucial in the case in which the 2nd argument is
there and is an instance of the first one).  But doesn't the second
sentence say explicitly that e.g. super(C) returns a "super object"
that is unbound?  Maybe by "superclass" you mean "base", a common
usage, but then the singular "the superclass" would be absurd.

I'm not sure what the practical use case for the 2nd argument being 
a type is:

>>> class A(object): a = 23
...
>>> class B(object): a = 45
...
>>> class C(A, B): a = 67
...
>>> C.a
67
>>> super(A, C).a
45

but I don't know how one would get, from C, some object whose
attribute named 'a' is worth 23.  So, I guess I just don't 
understand this part of super's behavior.


Alex





More information about the Python-list mailing list