Two classes problem

Steven Bethard steven.bethard at gmail.com
Wed Feb 2 15:27:24 EST 2005


Caleb Hattingh wrote:
> ===file: a.py===
> # module a.py
> test = 'first'
> class aclass:
>     def __init__(self, mod, value):
>         mod.test = value                # Is there another way to refer 
> to  the module this class sits in?
> ===end: a.py===

You can usually import the current module with:

__import__(__name__)

so you could write the code like:

test = 'first'
class aclass:
     def __init__(self, value):
         mod = __import__(__name__)
         mod.test = value

or you could use globals() like:

test = 'first'
class aclass:
     def __init__(self, value):
         globals()['test'] = value

> ===file: b.py===
> # file b.py
> import a
> x = a.aclass(a,'monkey')
> print a.test
> ===end: b.py===

If you used one of the solutions above, this code would be rewritten as:

import a
x = a.aclass('monkey')
print a.test


To the OP:

In general, this seems like a bad organization strategy for your code. 
What is your actual use case?

Steve



More information about the Python-list mailing list