簡體   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