首页 > 解决方案 > 有没有办法在python中循环这些元素的函数调用?

问题描述

我想循环这些元素的函数调用...有可能吗?

 class ClassName:
      def __init__(self, property):
        self.property = property
      def printclass(self):
        print(self.property)

e1 = ClassName(...)
e1.printclass()
e2 = ClassName(...)
e2.printclass()
e3 = ClassName(...)
e3.printclass()
...

这就是我试图做的......它没有用

elements = [e1, e2, e3,...]

for x in elements:
  print(x.printclass())

这些只是一些注释...不是代码

标签: pythonfunctionloopsclasscall

解决方案


如果我没有误解您的问题,那么这是您可以做到的一种方法-

class ClassName:
    def __init__(self, property):
        self.property = property
    def printclass(self):
        print(self.property)
    
instances = [ClassName('send_property_here') for i in range(10)]
for e in instances:
    print(e.printclass)
  1. 首先修复现有代码上的一些错字。例如,在从ClassName:创建实例时缺少结尾def和缺少必需的参数__init__
  2. List您可以使用和创建类实例range
  3. 迭代该实例列表并调用printclass()

推荐阅读