简体   繁体   English

Python类返回多个实例

[英]Python class returning multiple instances

I'm musing over the design of a class. 我在想一堂课的设计。 Currently, I have a list comprehension over a list of data that instantiates an instance of the class on each member of the list, thus returning me a list of instances of my class. 当前,我对数据列表有一个列表理解,该数据实例化了列表的每个成员上的类的实例,因此返回了我的类的实例的列表。

Would it be better, or indeed possible, to have instead a class method that takes a list and returns a list of instances? 改而采用一个接受列表并返回实例列表的类方法,会更好或更切实可行吗?

Essentially, I'm wondering, would: 我想知道的是,本质上:

data = [lots of data]
[MyClass(point) for point in data]

or 要么

@classmethod
def from_list(cls, data_list):
    return [cls(point) for point in data_list]

be better/more pythonic? 更好/更多pythonic? If it matters, in the usage I intend, I will always be instantiating the class from a list of data. 如果很重要,在我打算的用法中,我将始终从数据列表中实例化该类。

As it stands, there isn't much to choose between them. 就目前而言,它们之间没有太多选择。 However, the @classmethod has one major plus point; 但是, @classmethod有一个主要的加分点; it is available to subclasses of MyClass . 它可用于MyClass子类。 This is far more Pythonic than having separate functions for each type of object you might instantiate in a list. 与为您可能在列表中实例化的每种类型的对象具有单独的功能相比,这具有更多的Python风格。

I would argue that the first method would be better (list comprehension) since you will always be initializing the data from a list. 我认为第一种方法会更好(列表理解),因为您将始终从列表中初始化数据。 This makes things explicit. 这使事情变得明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM