Python 丢失对象列表

Python losing list of objects

当我执行这个程序时,我得到一个空列表:

我希望它创建对象列表并将对象附加到 obj_list_addresses 列表。

然后,当我调用 get_good_addresses() 时,我希望它返回该列表并仅对列表中的每个对象执行代码 returns empty [] 几乎就像它得到覆盖。

我是 python 的新手,我知道我遗漏了一些重要的东西。

主要:

from address import Address
from address_processor import AddressProcessor
addresses=[]
addresses = open('test.txt').read().splitlines()
proccess_addresses = AddressProcessor(addresses)
proccess_addresses.create_addresses_obj()
proccess_addresses.get_good_addresses()

地址处理器Class:

import multiprocessing
from address import Address

class AddressProcessor(object):
    """AddressProcessor will process a txt file with addresses"""

    def __init__(self, addresses):

        self.addresses = addresses
        self.return_addresses = []
        self.obj_list_addresses = []

    def create_addresses_obj(self):
        jobs = []
        for address in self.addresses:
            process = multiprocessing.Process(target=self.worker, args=(address,))
            jobs.append(process)
            process.start()
        for job in jobs:
            job.join()
        print('created objects for addresses in text file')

    def worker(self, address):

        obj = Address(address)
        self.obj_list_addresses.append(obj)

    def get_good_addresses(self):

        print self.obj_list_addresses

地址Class:

from string import replace
from pprint import pprint

class Address(object):

"""
This is address class send it an address it will look up
the addy and return json string of the parcels that matched the address 
then update status if it was the only one returned its good if not its bad
"""

def __init__(self, address):

    self.address = address
    self.status = ''
    self.json_string = ''

    self.set_json_string()

def get_address(self):
    return self.address

def set_json_string(self):

    r = requests.get('urlbasegoeshere'+replace(self.address," ","+")+'&pagesize=40&page=1')
    self.json_string = r.json
    self.set_status()

def set_status(self):

    if len(self.json_string) == 1:
        self.status = 1

    elif len(self.json_string)!=1:
        self.status = 0

def get_status(self):
    return self.status

为什么要使用 'multiprocessing' 创建地址对象?不同的进程不共享内存,即它们不共享对象。这不是 python 的事情,无论你使用什么语言都是一样的。

替换这三行

        process = multiprocessing.Process(target=self.worker, args=(address,))
        jobs.append(process)
        process.start()

        self.worker(address)