Question about accessing class-attributes.

Michele Simionato mis6 at pitt.edu
Fri May 2 17:14:12 EDT 2003


Alex Martelli <aleax at aleax.it> wrote in message news:<7Uwsa.33378$3M4.944644 at news1.tin.it>...
> 
> Sorry, you still haven't made your point clear to me.  What IS
> the added value of that "__superclass__" attribute when its whole
> point now seems to be that in the typical case it does nothing?

Have a __superclass__ attribute of super would solve the
following tricky cases:

#tricky case #1

class A(object): a=2
class B(object):
    class __metaclass__(type):
        a=2

class C(A,B): pass

assert superclass(A,C).a is 2 # okay
super(A,C).a # attribute error


#tricky case #2

class A(object): a=2
class B(object):
    class __metaclass__(type):
        def __getattr__(cls,name):
            if name=='a': return 2

class C(A,B): pass

superclass(A,C).a is 2 #okay
super(A,C).a # attribute error

However, I do agree that these are very special cases not worth big
consideration; moreover I can implement my own superclass()
function with two lines of code. Simply I thought the ability of
retrieving the superclass from super was handy ...  since it seems
I am the only one who thinks so, and I can already do what I want with
little effort, I will retract my proposal ;)

> You asked for __superclass__ as an attribute of classes.  

Ah! Here is the source of the misunderstanding: I *never* asked for
__superclass__ as an attribute of generic classes, this would be
pretty stupid, a synonymous of cls.__bases__[0], not doing what I
want. I see now why you were confused.

> Now it seems that what you want is an extra attribute of the 'super'
> object -- or is it, that you want an attribute of all classes
> which is ALSO special in the super object?  

This is another point, completely unrelated to the previous one.
In my code, I do add a private attribute to all classes for help
with super, but I was not talking about that.  But since you raised
the point ...

What I do is to add a private attribute __thisclass to any class via
a custom metaclass; then I can write code like


class C:
	__metaclass__=KnowsItself
        def __init__(self):
		super(self.__thisclass,self).__init__()

where KnowsItself add to C an attribute C._C__thisclass==C in such a
wayt that the previous code is the same that 

class C:
	__metaclass__=KnowsItself
        def __init__(self):
		super(C,self).__init__()

More verbose, but I avoid the repeat to name C in super and I am obsessive
in avoiding duplication of code ... ;)


                         Michele




More information about the Python-list mailing list