[2.2b2]: class variable and classmethod, subclass

Andreas Kostyrka andreas at mtg.co.at
Wed Nov 28 14:03:41 EST 2001


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Am Mittwoch, 28. November 2001 15:29 schrieb {-- Rot13 - Hateme:
> Thanks for your guys' answers.
>
> It sucks though. :) At least subclasses should not share
> the class variables with their parents. Why does it make
> sense?
Well, you have to seperate objects that can be modified in place, and
constant objects (strings, numbers, tuples, etc.)

Consider the following program:
class A:
    a=123
    b=[]
    def x(klass,v):
        klass.a=v
        klass.b.append(v)
    x=classmethod(x)

    def str(klass,lab):
        return "%s: a=%3d(%08x) %-7s(%08x)" % (lab,
                                                  klass.a,id(klass.a),
                                                  klass.b,id(klass.b),)
    str=classmethod(str)

class B(A):
    pass

print A.str("A"),B.str("B")
B.x(100)
print A.str("A"),B.str("B")

# output:
#A: a=123(0812828c) []     (08122cd4) B: a=123(0812828c) []     (08122cd4)
#A: a=123(0812828c) [100]  (08122cd4) B: a=100(08128298) [100]  (08122cd4)

When you look at A.x, you can see, that it rebind klass.a to a new object.
(Very important: = just labels a reference in python. It's not a classical 
assignment operator)
Because of this, when B.x is called, B.a is bound to a different object then 
A.a.

klass.b OTOH is not rebound, but modified in place. So it A.b and B.b 
continue to be the same object.

Andreas
- -- 
Andreas Kostyrka; Raiffeisenstr. 16/9; 2320 Zwölfaxing
Tel: +43/676/4091256; Fax: +43/1/7065299
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8BTUTHJdudm4KnO0RAtMhAJ9TiruGtHSaRD1ITYevkAW4Ye4RMQCfSOlL
S2AUkgldPvQaZxyfbzhMAt4=
=C/Jw
-----END PGP SIGNATURE-----




More information about the Python-list mailing list