Python类:基类方法中的变量子类创建

时间:2012-02-17 20:38:17

标签: python

这是我试图解决的编码问题...我有一个基类,让我们说动物,它有两个子类,比如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制作任意大量的子类。

3 个答案:

答案 0 :(得分:10)

您写道:

  

这不好,因为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())或实例上调用它;无论哪种方式,该方法仍然接收类作为第一个参数。

答案 1 :(得分:3)

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)

答案 2 :(得分:3)

你的方法将完全奏效!只需使用新的风格类。

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的回答一样。

相关问题