2

I have a class called Mobilesuits and each instance of that class has an attribute called coordinates, which consists of its grid coordinates, which are in a list(x,y,z).

I am trying to make a radar method which would detect how close a given vehicle is to other vehicles, but can't find a way to reference every objects coordinates simultaneously. Is there an easy way to do this in Python? I don't want to have to maintain a list of all vehicles and every time I want to perform a global change go through the whole list with a for loop, but that is the only way I can think of.

0

2 Answers 2

1

Save a reference to each instance in a class-level list. IMO it's not that tough to maintain, nor it is a global list.

class Mobilesuits:
     instances = []
     def __init__(self):
         Mobilesuits.instances.append(self)

Obviously add whatever else you need to the __init__. If you look at Mobilesuits.instances from outside the class, you'll get a list of the instances of it.

If you really really really don't want to keep a list you can do something really questionable (and honestly, idk how safe) with gc:

import gc

mobile_suits = [o for o in gc.get_objects() if isinstance(o, Mobilesuits)]

but seriously, just keep a list

1
  • Wow, this is absolutely brilliant. I didn't know about this functionality before. Thanks a lot! You made my night Jan 4, 2014 at 3:56
0

I don't want to have to maintain a list

It's what you are meant to do; and you would have to use loops anyway. You're effectively asking the language to create a list for you automatically. Well, why would it? Contrary to what you might expect, you almost always will not need or want a list of every single instance of a class ever created. In fact, it's entirely possible that you don't even really want that for your current program (whether you yet realize it or not). There are all kinds of possible reasons, in practice, why you might want to create instances that are not subject to the "usual" handling.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.