一个类的许多实例 [英] Many instances of a class

查看:94
本文介绍了一个类的许多实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用python编写各种动物的生活模拟.无法命名将要使用的类的每个实例,因为我无法知道将会有多少个实例.

I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.

所以,我的问题:

如何为对象自动命名?

我当时正在考虑创建一个"Herd"类,该类可以同时活着该类型的所有动物……

I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...

推荐答案

嗯,通常,您只需将所有这些实例填充到列表中,然后在该列表上进行迭代(如果您想对它们执行某些操作)即可.如果要自动跟踪创建的每个实例,还可以在类的构造函数中隐式添加到列表中,或者创建一个工厂方法来跟踪创建的实例.

Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track of the created instances.

这篇关于一个类的许多实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆