开发者

Create and retrieve object list in Python

I would like to keep a reference of the objects I've created in one script to use them in another script (without using shelve).

I would like something close to :

script 1

class Porsche(Car):
    """ class representing a Porsche """
    def __init__(self, color):      
        self.color = color


class Porsche_Container:
    # objects here 
    return objects

my_Porsche = Porsche开发者_如何转开发(blue)
my_Porsche2 = Porsche(red) 

script2

for object in Porsche_Container:
    print object.color

rgds,


The best way to do this is explicitly to construct the set of objects that you want to access. It is possible to list e.g. all global variables defined in the other script, but not a good idea.


script1

...
porsche_container = { myPorsche1, myPorsche2 }

script 2

import script1
for porsche in script1.porsche_container:
    ...


Are these scripts going to be run in different processes? If not the solution is pretty straight forward (see katriealex's answer).

If they are going to run in different processes then you'll need more complex solutions involving inter process communication.


I'm assuming you want only one process.

Use import, treat one 'script' as the main module and the other 'script' as a library module that you import. In my modified example script2.py is the main module and script1.py is the library.

script1.py

# -*- coding: utf-8 -*-

class Porsche(object):
 """ class representing a Porsche """
 def __init__(self, color):
            self.color = color

BLUE = 1
RED = 2

def make_porsche_list():
    return [Porsche(BLUE), Porsche(RED)]

script2.py

# -*- coding: utf-8 -*-

import script1

porsche_container = script1.make_porsche_list()

for object in porsche_container:
    print object.color

Output:

eike@lixie:~/Desktop/test> python script2.py
1
2
eike@lixie:~/Desktop/test> ls
script1.py  script1.py~  script1.pyc  script2.py  script2.py~
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜