如何在Python中迭代使用迭代创建的对象的方法



我试图通过在对象所属的类中使用类方法来迭代创建对象。因此,每次我调用该类方法时,它都会创建一个对象,并将其加载到带有适当idex的字典中(两者都是类变量(。当我想对每个对象调用相同的方法,但每次都要迭代并使用随机属性时,问题就来了。我的代码很大,所以在这里我用我想要的东西编写了另一个程序,这样更容易理解。

class new_class:
objects = {} #this dictionary stores all objects of this class
i = 0 #used to iterate the dictionary and define every object separately
def __init__(self):
pass
def method(self, random): #<-- here goes the random elements that the method should be called with
return random #sample usage of the random value
@classmethod
def object_creator(cls):
cls.i += 1
cls.objects[cls.i] = cls() <-- this creates a new object of its own class and adds it to the dictionary with the key of the also iterated "i" variable

while True:
new_class.object_creator()
#Here I want to call for the method of evey existing object with random attributes

使用字典及其索引以这种方式调用对象不起作用,因为它只调用最后创建的对象,因为当前索引属于他。

while True:
new_class.object_creator()
new_class.objects[new_class.i].method()

我不确定这是否可能,因为我必须";创建新代码";对于每个创建的对象。我找到的唯一伪解决方案是制作另一个循环,遍历字典的长度,并调用对象的方法,该对象的索引是循环的索引,但一次调用每个方法,而不是同时调用所有方法。

默认情况下,您的代码由单个线程按顺序执行,因此对该方法的调用将一个接一个地完成。但是调用所有对象的方法可能很快,因为计算机速度很快。从编程语言的角度来看,调用call_my_method_for_all_my_objects与调用int("14")没有什么不同。

如果你真的(真的(想让代码并行执行,你可以看看多线程多重处理,但这些都不是容易的话题。如果你实际上不想让程序执行得更快,或者真的需要同时执行多个代码,就不要麻烦它们。

使用dict而不是list不是真正的问题。

的问题

while True:
new_class.object_creator()
new_class.objects[new_class.i].method()

在循环的每次迭代中,它将创建一个新对象(以i为增量(,然后调用第i个对象(新创建的(方法。这意味着每个对象的方法只调用一次,并且按创建顺序也是i-升序。

至于解决方案,我建议您创建一个函数或方法来调用每个对象。我决定将其实现为类的静态方法:

class new_class:
objects = {}
i = 0
def __init__(self):
pass
def method(self, random):
return random
@classmethod
def object_creator(cls):
cls.i += 1
cls.objects[cls.i] = cls()
@staticmethod  # static
def call_each():
for i, obj in new_class.objects.items():  # iterate over the objects
print(obj.method(i))  # call each one's method, for example with its index

我是这样用的:

# let's create 3 items for demonstration purposes
new_class.object_creator(); new_class.object_creator(); new_class.object_creator()
print(new_class.objects)  # {1: <__main__.new_class object at 0x0000022B26285470>,
#  2: <__main__.new_class object at 0x0000022B262855C0>,
#  3: <__main__.new_class object at 0x0000022B262854A8>}
new_class.call_each()  # prints 1 2 3

如果您想为每个调用提供一个随机值,请将import random添加到脚本中,并将call_each方法更改为:

@staticmethod
def call_each():
for obj in new_class.objects.values():
print(obj.method(random.random()))

因此

new_class.call_each()  # prints 0.35280749626847374
#        0.22163283338299222
#        0.7368657784332368

如果这不能回答你的问题,请试着更加清楚你的问题。

最新更新