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.

2
  • 2
    Can you use a dict of fish? E.g.: fishids = dict((fishid, fish()) for fishid in range(1000)) Commented Jan 10, 2020 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. Commented Jan 10, 2020 at 16:20

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.