Overriding variables used by base classes

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Nov 14 14:42:42 CET 2003


google_mail at aristoweb.net (Corey Lubin) wrote in 
news:a64176a.0311140417.2ad0b51a at posting.google.com:

> [original.py]
> someGlobal=1
> 
> class Original:
>     def foo(self):
>         # Make use of someGlobal
> [/original.py]
> 
> [tainted.py]
> from original import *
> someGlobal=2
> 
> class Tainted(Original):
>     pass
> [/tainted.py]
> 
> How might one make it such that Tainted.foo makes use of
> tainted.someGlobal, rather than original.someGlobal? Must I use
> eval/exec? Note that the point is that I don't want to have to
> duplicate the definition of foo.

Make foo a classmethod, lose the globals altogether and make them class 
variables:

class Original:
    someVar = 42
    def foo(cls):
        print cls.someVar

    foo=classmethod(foo)

class Tainted(Original):
    someVar = 24

Original().foo() # prints 42
Tainted().foo() # prints 24

Oh, and lose the 'from original import *', just do 'import original' and 
refer to original.Original in your class definition.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list