当前位置: 动力学知识库 > 问答 > 编程问答 >

Python pass a class reference to another class during construction

问题描述:

I'm intending to create a data distributor class as a mutable class:

class DataDistributor(object):

def __init__(self):

self.target_trackid = -1

def next_sen(self):

self.target_trackid += 1

return self.target_trackid

So that I can globally keep a pointer on my data.

I have another class:

class Env(object):

def __init__(self, distributor):

self.distributor = distributor

self.target_trackid = 0 # init

def reset(self):

self.target_trackid = self.distributor.next_sen()

So that when I create many Env instances, each Env instance will get a different data point.

So I use this to create my instances:

ddist = DataDistributor()

env = Env(ddist)

envs = [pickle.loads(pickle.dumps(env)) for _ in range(12)]

envs[0].reset()

envs[1].reset()

envs[2].reset()

print envs[0].target_trackid

print envs[1].target_trackid

print envs[2].target_trackid

And the results are all the same: a bunch of 0s.

I'm not exactly sure how Python is handling this :( and if there is a viable solution to achieve what I want to achieve!

网友答案:

How about creating a class variable for keeping track of the objects created? Your simple class structure will be like:

class Env(object):
    my_counter = 0    # Your class variable

    def __init__(self, param1, param2):
        # some initialization
        Env.my_counter += 1   # increament everytime object is created
        # some logic

Sample run:

>>> e1 = Env('p11', 'p12')  # creation of first object
>>> Env.my_counter
1     # value of counter set as 1

>>> e1 = Env('p21', '22')   # creation of second object
>>> Env.my_counter
2     # value of counter set as 2

Passing object of different class just for tracking the created object of some other class, it is definitely not the right approach.

网友答案:

pickle.load will create different objects which means the datadistributor variable in each env object will refere

分享给朋友:
您可能感兴趣的文章:
随机阅读: