Overriding variables used by base classes

Hung Jung Lu hungjunglu at yahoo.com
Sat Nov 15 04:53:17 EST 2003


google_mail at aristoweb.net (Corey Lubin) wrote in message 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? 

Use

[tainted.py]
import original
original.someGlobal=2

class Tainted(original.Original):
    pass
[/tainted.py]

-------------------------

(a) Python's namespace mechanism is hard to understand for newcomers.
It is a fact, no matter how hard people try to deny it: your question
has been asked a few hundred times before. But once you understand
that assignment in Python is name binding and is very different from
assignment in other languages like C/C++, you'll get used to it. Same
with import and from ... import ... statements.

Namespace mechanism is the heart and soul of Python. When you have
more time, try to read more and understand it. Otherwise you'll run
into surprises in many places. When writing each line of Python code,
you need to keep in mind what namespaces you are dealing with: an
object's namespace? local dictionary? global dictionary? built-in?

(b) Stay with your present approach. There is still no need for exec.
Python is powerful enough to allow you to tweak many aspects of
existing modules/classes/functions/methods without needing to evaluate
code strings. What you are doing is called "patching". You are making
a patch for existing module/class. If the changes are like adding
attributes, surround a method with some around codes, those can be
done easily with inheritance. If you need to override a foreign class
method because you want to change the code in some spots inside the
method, and the foreign class is used by other foreign
classes/modules, you can write your code in your own module/class and
replace the foreign implementation. Look into the documentation for
the "new" module. In short, there are many ways to dynamically modify
Python modules/classes/functions/methods.

(c) More generally, what you want to do falls into the arena of
Aspect-Oriented Programming. No need to understand it, now. But keep
it in mind.

regards,

Hung Jung




More information about the Python-list mailing list