[英]Python: how to get create instance of a class within same class?
I am trying to create a class which has a static method which returns list of its own instances. 我正在尝试创建一个具有静态方法的类,该方法返回其自身实例的列表。 How can I do this without referring to the class name: 不参考类名怎么办?
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
This code works perfectly fine. 这段代码工作得很好。 But I have to reuse this code (copy+paste) in various classes, like Bus, Ship, Plane, Truck . 但是我必须在各种类(例如Bus,Ship,Plane,Truck )中重用此代码(复制并粘贴)。
I am looking for a way to reuse above code in all these classes by making a generic way of instantiating instance of current class. 我正在寻找一种通过实例化当前类实例的通用方法在所有这些类中重用以上代码的方法。 Basically replace line #11 from: 基本上从以下位置替换第11行:
11: instance = MyCar(i)
to a more generic state which can be reused in any class. 到可以在任何类中重用的更通用的状态。 How can I do this ? 我怎样才能做到这一点 ?
Use a class method, not a static method. 使用类方法,而不是静态方法。 That way, assuming for example that Bus
inherits MyCar
, then Bus.get_cars_from()
will call the inherited MyCar.get_cars_from
, but the cls
argument will be set to Bus
. 这样,假设Bus
继承了MyCar
,则Bus.get_cars_from()
将调用继承的MyCar.get_cars_from
,但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
Also, a list comprehension makes this a more-efficient one-liner: 同样,列表理解使这成为一种更有效率的单行代码:
@classmethod
def get_cars_from(cls, start=0, end=10):
return [cls(i) for i in range(start, end)]
(but use xrange
instead of range
in Python 2). (但使用xrange
代替Python 2中的range
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.