Allen Nie Allen Nie - 1 year ago 46
Python Question

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
instances, each
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)]


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!

Answer Source

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.