gpt4 book ai didi

Python:如何在同一个类中创建类的实例?

转载 作者:行者123 更新时间:2023-12-01 04:19:56 25 4
gpt4 key购买 nike

我正在尝试创建一个具有静态方法的类,该方法返回其自己的实例列表。如何在不引用类名的情况下执行此操作:

 1: class MyCar(object):
2: def __init__(self, number):
3: self._num = number
4:
5: @staticmethod
6: def get_cars_from(start=0, end=10):
7: """ This method get a list of cars from number 1 to 10.
8: """
9: return_list = []
10: for i in range(start, end):
11: instance = MyCar(i)
12: return_list.append(instance)
13: return return_list

这段代码工作得很好。但我必须在各种类中重用此代码(复制+粘贴),例如巴士、船舶、飞机、卡车

我正在寻找一种通过创建实例化当前类实例的通用方法来在所有这些类中重用上述代码的方法。基本上将 #11 行替换为:

  11: instance = MyCar(i)

到一个更通用的状态,可以在任何类中重用。我该如何做到这一点?

最佳答案

使用类方法,而不是静态方法。这样,假设 Bus 继承 MyCar,那么 Bus.get_cars_from() 将调用继承的 MyCar.get_cars_from code>,但 cls 参数将设置为 Bus

@classmethod
def get_cars_from(cls, start=0, end=10):
""" This method get a list of cars from number 1 to 10.
"""
return_list = []
for i in range(start, end):
instance = cls(i)
return_list.append(instance)
return return_list

此外,列表理解使其成为更高效的单行代码:

@classmethod
def get_cars_from(cls, start=0, end=10):
return [cls(i) for i in range(start, end)]

(但在 Python 2 中使用 xrange 而不是 range)。

关于Python:如何在同一个类中创建类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com