【问题标题】:apply python class methods on list of instances在实例列表上应用 python 类方法
【发布时间】:2018-11-18 08:53:49
【问题描述】:

我最近从 Matlab 迁移到 Python,想将一些 Matlab 代码转移到 Python。但是突然出现了一个障碍。

在 Matlab 中,您可以定义一个类及其方法并创建实例的 nd 数组。好处是您可以将类方法应用于实例数组,只要方法被编写好,它就可以处理数组。现在在 Python 中,我发现这是不可能的:将类方法应用于实例列表时,它不会找到类方法。下面是我如何编写代码的示例:

class testclass(): 
   def __init__(self, data):
      self.data = data
   def times5(self):
      return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
times5(classlist)

这将在 times5(classlist) 行上产生错误。现在这是一个简单的示例,解释了我想要做什么(最终类将有多个 numpy 数组作为变量)。

在 Python 中获得这种功能的最佳方式是什么?我想这样做的原因是因为它允许批处理操作并且它们使类更强大。我能想到的唯一解决方案是定义第二个类,其中包含第一个类的实例列表作为变量。批处理需要在第二类中实现。

谢谢!

【问题讨论】:

  • 一旦你熟悉了核心 Python,你应该考虑学习 Numpy。 Numpy 可以有效地对数字数组进行算术运算,但它不会加快对一般 Python 对象的方法的执行。
  • 您可以使用列表理解创建该列表:[u.times5() for u in classlist]。您可以填充输入列表,如classlist = [testclass(u) for u in (1, 10, 100)]。如果您实际上不需要保留classlist,则可以将它们组合起来。
  • 你必须在类本身上使用方法......所以它被定义为testclass()的方法,所以你必须这样做:instance = testclass(1)

标签: python list matlab class


【解决方案1】:

更新:

在你的评论中,我注意到这句话,

例如一个函数,它获取列表中第一个类的数据并减去所有后续类的数据。

这可以通过reduce函数解决。

class testclass():
   def __init__(self, data):
      self.data = data
   def times5(self):
      return testclass(self.data * 5)

from functools import reduce
classlist = [x.data for x in [testclass(1), testclass(10), testclass(100)]]
result = reduce(lambda x,y:x-y,classlist[1:],classlist[0])
print(result)

原答案:

其实你需要的是List Comprehensions

请让我给你看代码

class testclass(): 
   def __init__(self, data):
      self.data = data
   def times5(self):
      return testclass(self.data * 5)

classlist = [testclass(1), testclass(10), testclass(100)]
results = [x.times5() for x in classlist]
print(results)

【讨论】:

  • 感谢您的回答,但是我想让列表理解部分远离班级用户。这个批处理功能并不总是在列表中的每个实例上执行一个方法,而是会做更复杂的事情。例如一个函数,它获取列表中第一个类的数据并减去所有后续类的数据。
  • @StefanVR 我更新了答案来解决你的新问题。
猜你喜欢
  • 2023-04-01
  • 2011-09-22
  • 2015-06-10
  • 2011-06-29
  • 1970-01-01
  • 2014-11-21
  • 2016-01-12
  • 2010-10-03
  • 1970-01-01
相关资源
最近更新 更多