On 16 avr, 09:42, "Prashant" <shikha_saxena2...@yahoo.comwrote:
I was wondering is there any way to do this:
I have written a class in python and __init__ goes like this:
def __init__(self):
self.name = 'jack'
self.age = 50
import data
now here there is data.py in the same directory and contents are like:
self.address = 'your address'
self.status = 'single'
The problem is 'self' is giving some error here. I need to know if
somehow I can do this. It's like inserting the script as it's part of
the file itself.
The purpose of import is to build a module object, which implies
executing the module file but in a new context.
If you simply want to execute some code in a file, you can try
execfile("filename"):
In [243]: class A(object):
.....: def __init__(self):
.....: execfile("test.py")
.....:
In [244]: a=A()
In [245]: a.a
Out[245]: 1
In [246]: open("test.py").read()
Out[246]: 'self.a = 1\n'
But do you really want to execute some arbitrary code or to initialize
values with some kind of configuration file?
>
Cheers