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

amp*_*ron 3 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'
Run Code Online (Sandbox Code Playgroud)

所以我想避免为Dogs和Cats编写一个make_baby()方法,因为这个方法是除了返回的类之外的方法完全一样.我还想避免一堆if语句,因为我想为Animal制作任意大量的子类.

kin*_*all 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
Run Code Online (Sandbox Code Playgroud)

您可以在类(例如Animal.make_baby()Dog.make_baby())或实例上调用它; 无论哪种方式,该方法仍然接收类作为第一个参数.

  • 如果需要实例,则类方法将不合适,例如,如果涉及遗传.虽然在那种情况下,通过动态打字,没有一种自然的方法可以防止间隔 - 你知道什么,忘记我说了什么. (2认同)