[英]Iterate over python class
I am learning how to do OOP with python.我正在学习如何使用 python 进行 OOP。 I would like to create a class
B
that contains an array/list of class A
and execute a function in a for loop.我想创建一个包含类
B
的数组/列表的类A
并在 for 循环中执行一个函数。
Here is an example:这是一个例子:
class A:
def __init__(self, name):
self.name = name
def printSomething(self):
print (self.name)
class B:
def __init__(self, listOfNames):
# struture to store a list of objects A based on the list of names supplied
def printSomething2(self):
for i in # struture to store a list of objects A based on the list of names supplied :
i.printSomething()
names = ["a,b,c,d"]
obj = B(names)
obj.printSomething2()
what python structure is suitable for storing multiple objects?什么python结构适合存储多个对象? How can I set the size of it based on the input of the class?
如何根据类的输入设置它的大小? For can I iterate over the created structure to call a function?
我可以遍历创建的结构来调用函数吗?
Best Regards此致
You could just use:你可以只使用:
class B():
def __init__(self,listOfNames):
self.name_objs = []
for name in listOfNames:
self.name_objs.append(A(name))
def printSomething2(self):
for i in self.name_objs:
i.printSomething()
Still this is dynamic and getting the size to set this before is rather hard but this would work仍然这是动态的,并且之前设置它的大小相当困难,但这会起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.