Overriding variables used by base classes
Hung Jung Lu
hungjunglu at yahoo.com
Sat Nov 15 10:53:17 CET 2003
google_mail at aristoweb.net (Corey Lubin) wrote in message news:<a64176a.0311140417.2ad0b51a at posting.google.com>...
> class Original:
> def foo(self):
> # Make use of someGlobal
> from original import *
> class Tainted(Original):
> How might one make it such that Tainted.foo makes use of
> tainted.someGlobal, rather than original.someGlobal?
(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
(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.
More information about the Python-list