python - 有没有办法在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())
这些只是一些注释...不是代码
解决方案
如果我没有误解您的问题,那么这是您可以做到的一种方法-
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)
- 首先修复现有代码上的一些错字。例如,在从ClassName
:
创建实例时缺少结尾def
和缺少必需的参数__init__
List
您可以使用和创建类实例range
。- 迭代该实例列表并调用
printclass()
推荐阅读
- angular - 如何在Angular中接受多个选中的复选框?
- c# - RayCastHit2D 未检测到播放器
- angular - 绕过SecurityTrustHtml Angular 6后文本框不起作用
- python - 何时转换 GPS 坐标
- javascript - HTML DOM 元素的 ScrollTop 属性在不同的监视器上给出整数/双精度值
- android - 从android中的SharedPreferences中删除对象
- ios - 如果前一个单元格的文本字段已填写,则将单元格添加到 UITableView
- cmake - cmake 未定义类型名 loc_t (gpslib)
- yaml - Apiary 编辑器上的 Swagger 将默认值 0 呈现为 null
- javascript - Jquery Datepicker 未在 Bootstrap Popup 模式中显示