繁体   English   中英

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

[英]Python: how to get create instance of a class within same class?

我正在尝试创建一个具有静态方法的类,该方法返回其自身实例的列表。 不参考类名怎么办?

 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

这段代码工作得很好。 但是我必须在各种类(例如Bus,Ship,Plane,Truck )中重用此代码(复制并粘贴)。

我正在寻找一种通过实例化当前类实例的通用方法在所有这些类中重用以上代码的方法。 基本上从以下位置替换第11行:

  11: instance = MyCar(i)

到可以在任何类中重用的更通用的状态。 我怎样才能做到这一点 ?

使用类方法,而不是静态方法。 这样,假设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

同样,列表理解使这成为一种更有效率的单行代码:

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

(但使用xrange代替Python 2中的range )。

暂无
暂无

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

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