簡體   English   中英

Python類:基類方法中的變量子類創建

[英]Python Classes: Variable subclass creation in the base class's methods

這是我試圖解決的編碼問題...我有一個基類,讓我們說動物,它有兩個子類,比如Dog和Cat。 我的類Animal有一個方法,make_baby(),Dog和Cat都會繼承。 我無法解決的訣竅是我希望返回值是調用函數但具有不同屬性值的子類的新實例,即Dog.make_baby()應該返回一個新的Dog和Cat.make_baby( )將返回一只新貓。

我以前嘗試返回“type(self)()”,但這並不好,因為type()返回一個類型對象,而不是一個類。

這是完整的示例代碼:

Class Animal():
  def __init__(self, color):
    self.color = color
  def make_baby():
    new_color = rand_color # a randomly chosen color
    return #??? new class of the same type that called the method

Class Dog(Animal):
  def pet():
    print '*pant*'

Class Cat(Animal):
  def pet():
    print 'purrr'

所以我想避免為Dogs和Cats編寫一個make_baby()方法,因為這個方法是除了返回的類之外的方法完全一樣。 我還想避免一堆if語句,因為我想為Animal制作任意大量的子類。

你寫了:

這不好,因為type()返回一個類型對象,而不是一個類。

如果您使用的是新式類,則類型一個類。 如果您正在使用Python 3,那么您已經設置好了; 所有Python 3類都是“新風格”。 如果您正在使用Python 2.x,則從object (或從對象派生的其他內容,如任何內置Python類型)派生您的類。

但是你真正想要的是一個類方法,在這里你可以獲得對自動傳入的類的引用。

class Animal(object):

  def __init__(self, color):
    self.color = color

  @classmethod
  def make_baby(cls):
    return cls(rand_color)   # randomly-chosen color

您可以在類(例如Animal.make_baby()Dog.make_baby() )或實例上調用它; 無論哪種方式,該方法仍然接收類作為第一個參數。

type()可用於構造全新的類。 你想要的是:

class Animal():
  def __init__(self, color):
    self.color = color

  def make_baby(self):
    new_color = rand_color # a randomly chosen color
    return self.__class__(new_color)

你的方法將完全奏效! 只需使用新的樣式類。

Class Animal(object):
  def __init__(self, color):
    self.color = color
  def make_baby(self):
    new_color = rand_color # a randomly chosen color
    return type(self)(new_color)

Class Dog(Animal):
  def pet():
    print '*pant*'

Class Cat(Animal):
  def pet():
    print 'purrr'

但是,如果make_baby(self) 依賴於self細節,那么你想要的是一個類范圍的工廠方法,就像@ Kindall的答案一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM