【问题标题】:Is there a way to loop the function call of these elements in python?有没有办法在python中循环这些元素的函数调用?
【发布时间】:2020-12-26 12:53:25
【问题描述】:

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

 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())

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

【问题讨论】:

  • 究竟是什么不起作用?您的代码的期望输出和实际输出是什么?

标签: python function loops class call


【解决方案1】:

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

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. 首先修复现有代码上的一些错字。例如,在 def 上从 ClassName 创建实例时缺少 : 结尾 def 并缺少必需的参数@
  2. 您可以使用Listrange 创建类实例。
  3. 迭代该实例列表并调用printclass()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多