0

So far I mostly used Python for data analysis but for some time try to implement stuff. Right now I'm trying to implement a toxicokinetic-toxicodynamic model for a fish to analyse the effect of chemicals on them.

So given the following code:

import numpy as np

class fish():

def __init__(self):
    self.resistance_threshold = np.random.normal(0,1)


My question is now, say I would like to initialize multiple instances of the fishclass (say 1000 fish), each with a different resistance to a chemical in order to model an agent-based population. How could one achieve this automatically?

I was wondering if there is something as using for example an index as part of the variable name, e.g.:

for fishid in range(0,1000):
    fishfishid = fish() # use here the value of fishid to become the variables name. E.g. fish1, fish2, fish3, ..., fish999

Now even if there is a possibility to do this in Python, I always have the feeling, that implementing those 1000 instances is kinda bad practice. And was wondering if there is like an OOP-Python approach. Such as e.g. setting up a class "population" which initializes it within its own __init__function, but how would I assign the fish without initializing them first?

Any tipps, pointers or links would be greatly appreciated.

Pienatt
  • 51
  • 5
  • 2
    Can you use a dict of fish? E.g.: `fishids = dict((fishid, fish()) for fishid in range(1000))` – Matt Shin Jan 10 '20 at 15:52
  • Matt Shin's solution addresses the issue of being able to find a `Fish` object by fishid. Dictionaries make for very fast look up times, too. – Conner M. Jan 10 '20 at 16:20

1 Answers1

1

You can create a class FishPopulation and then store there all the Fish you need based on the size argument. For example, something like this would work:

import numpy as np


class Fish:
    def __init__(self):
        self.resistance_threshold = np.random.normal(0, 1)


class FishPopulation:
    def __init__(self, size=1000):
        self.size = size
        self.fishes = [Fish() for _ in range(size)]

You can iterate over it like this:

fish_population = FishPopulation(size=10)
for fish in fish_population.fishes:
    print(fish.resistance_threshold)

>>> 
    -0.9658927669391391
    -0.5934917229482478
    0.8827336199040103
    -1.5729644992077412
    -0.7682070400307331
    1.464407499255235
    0.7724449293785645
    -0.7296586180041732
    -1.1989783570280217
    0.15716170041128566

And you can access their indexes like this:

print(fish_population.fishes[0].resistance_threshold)

>>> -0.9658927669391391
marcos
  • 4,473
  • 1
  • 10
  • 24