简体   繁体   English

如何同时引用所有类实例?

[英]How do I reference all class instances at the same time?

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). 我有一个称为Mobilesuits的类,该类的每个实例都有一个称为坐标的属性,该属性由其网格坐标组成,这些坐标位于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? 有没有简单的方法可以在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. 我不想维护所有车辆的清单,而每次我想要进行全局更改时,都需要使用for循环遍历整个清单,但这是我唯一能想到的方法。

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. IMO维护起来并不难,也不是全球清单。

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

Obviously add whatever else you need to the __init__ . 显然,您需要将其他任何内容添加到__init__ If you look at Mobilesuits.instances from outside the class, you'll get a list of the instances of it. 如果您从类外部查看Mobilesuits.instances ,则将获得其实例的列表。

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: 如果您真的真的不想保留列表 ,则可以使用gc进行一些可疑的操作(老实说,idk的安全性):

import gc

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

but seriously, just keep a list 但是认真一点,只要列出一个清单

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. 实际上,出于各种原因,您可能想创建不受“常规”处理的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM