insert python script in current script

P

Prashant

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.

Cheers
 
C

colas.francis

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?
 
N

Nick Stinemates

Can you give a use case for doing this. You would most likely be better doing:

class person(object):
def __init__(self, name=None, age=None):
self.name=name
self.age=age


personInstance=person(name='jack', age='50)

-Larry

Could it also be that he would like to have a base class? Cause that's
what It sounds like to me!

class Base:
def __init__(self):
self.address = "address"
self.status = 1 //use numbers instead of strings :)

class Person(Base):
def __init__(self):
Base.__init__(self)
# now you have the self.address, self.status
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top