Two classes problem
Steven Bethard
steven.bethard at gmail.com
Thu Feb 3 01:55:05 EST 2005
Gurpreet Sachdeva wrote:
> The purpose is, I pass a list to a class in a module but I want to use
> that list out of the scope of that class and that too not in any other
> class or a function but in the main program...
> The problem is that when I import that, the statements in the module
> which are not in the class are executed first and then the variable
> gets intiallised...
> I will explain with the example...
>
> -global test
> -
> -class a:
> - def __init__(self,test):
> - global test
> - print test
> -
> -print 'Outside: '+test
>
> I want to print that variable test which I am giving to the class as
> an argument, in the scope of main...
> I know it is not a good way of programming but my situation is like this...
> But is this possible or not? If I pass test as 'Garry' can I (by any
> way) print 'Outside: Garry' with that print statement... (in the main
> scope)
Probably a better approach for this would be something like:
class A(object):
def __init__(self, test):
self.test = test
def printtest(self):
print 'Outside: %s' % self.test
where your code in your main module looks something like:
import amodule
a = amodule.A('Garry')
a.printtest()
The __init__ method is used for initializing *instances* of a class, so
using the __init__ method to initialize a module-level variable doesn't
really make much sense. If you really want to play around with
module-level variables, you probably want to modify them with
module-level functions, e.g.:
test = 'default'
def a(val):
global test
test = val
def printtest():
print 'Outside: %s' % test
where your code in your main module looks something like:
import amodule
amodule.a('Garry')
amodule.printtest()
Note that I've moved all your code that would normally be executed at
module import time into the 'printtest' function. This way you can
execute this code after import.
If you really need to have the code executed at the same time as the
module is imported, another option would be to exec your code in an
empty module instead of importing it:
py> a_module_str = """print 'Outside: %s' % test"""
py> a_module = new.module('a')
py> a_module.test = 'Garry'
py> exec a_module_str in a_module.__dict__
Outside: Garry
Here I create an empty module, set its 'test' attribute to 'Garry', and
then execute the rest of your code (e.g. the print statement). This is
certainly my least favorite approach, but it seems to do the closest
thing to what you're asking for.
Steve
More information about the Python-list
mailing list