python - 在python中用父类方法覆盖__init__

标签 python inheritance constructor class-method

我想做如下的事情(在 Python 3.7 中):

class Animal:

    def __init__(self, name, legs):
        self.legs = legs
        print(name)

    @classmethod 
    def with_two_legs(cls, name):
        # extremely long code to generate name_full from name
        name_full = name
        return cls(name_full, 2)

class Human(Animal):

    def __init__(self):
        super().with_two_legs('Human')

john = Human()

基本上,我想用父类的工厂类方法覆盖子类的 __init__ 方法。但是,编写的代码不起作用,并引发:

TypeError: __init__() takes 1 positional argument but 3 were given

我认为这意味着 super().with_two_legs('Human')Human 作为 cls 变量传递。

1) 为什么这不像写的那样工作?我假设 super() 会返回父类(super class)的代理实例,所以 cls 会是 Animal 对吧?

2) 即使是这种情况,我也不认为这段代码能达到我想要的效果,因为类方法返回 Animal 的实例,但我只想初始化 Human 和 classmethod 一样,有什么方法可以实现我想要的行为吗?

我希望这不是一个很明显的问题,我找到了 documentation关于 super() 有点困惑。

最佳答案

super().with_two_legs('Human') 实际上确实调用了 Animalwith_two_legs,但它通过了 Human 作为 cls,而不是 Animalsuper() 使代理对象仅用于辅助方法查找,它不会改变传递的内容(它仍然是相同的 selfcls 它起源于)。在这种情况下,super() 甚至没有做任何有用的事情,因为 Human 不会覆盖 with_two_legs,所以:

super().with_two_legs('Human')

表示“从定义它的层次结构中Human上方的第一个类调用with_two_legs”,并且:

cls.with_two_legs('Human')

表示“在层次结构中以定义它的 cls 开头的第一个类上调用 with_two_legs”。只要 Animal 下的类没有定义它,它们就会做同样的事情。

这意味着您的代码在 return cls(name_full, 2) 处中断,因为 cls 仍然是 Human,而您的 Human .__init__ 不接受任何超出 self 的参数。即使您费尽心思让它工作(例如,通过添加两个您忽略的可选参数),这也会导致无限循环,因为 Human.__init__ 称为 Animal.with_two_legs ,它又试图构造一个 Human,再次调用 Human.__init__

您尝试做的不是一个好主意;替代构造函数就其性质而言,依赖于类的核心构造函数/初始化器。如果您尝试创建依赖于备用构造函数的核心构造函数/初始化程序,则您创建了循环依赖项。

在这种特殊情况下,我建议避免使用备用构造函数,而是始终显式提供 legs 计数,或者使用执行的中间 TwoLeggedAnimal 类您的替代构造函数的任务。如果你想重用代码,第二个选项只是意味着你的“从名称生成 name_full 的超长代码”可以放在 TwoLeggedAnimal__init__ 中;在第一个选项中,您只需编写一个 staticmethod 来分解该代码,以便 with_two_legs 和其他需要使用它的构造函数都可以使用它。

类层次结构类似于:

class Animal:
    def __init__(self, name, legs):
        self.legs = legs
        print(name)

class TwoLeggedAnimal(Animal)
    def __init__(self, name):
        # extremely long code to generate name_full from name
        name_full = name
        super().__init__(name_full, 2)

class Human(TwoLeggedAnimal):
    def __init__(self):
        super().__init__('Human')

常见的代码方法是这样的:

class Animal:
    def __init__(self, name, legs):
        self.legs = legs
        print(name)

    @staticmethod
    def _make_two_legged_name(basename):
        # extremely long code to generate name_full from name
        return name_full

    @classmethod 
    def with_two_legs(cls, name):
        return cls(cls._make_two_legged_name(name), 2)

class Human(Animal):
    def __init__(self):
        super().__init__(self._make_two_legged_name('Human'), 2)

旁注:即使您解决了递归问题,您尝试做的事情也不会起作用,因为 __init__ 不会制作新实例,它会初始化现有实例。因此,即使您调用 super().with_two_legs('Human') 并且它以某种方式工作,它也会创建并返回一个完全不同的实例,但不会对 self 做任何事情由 __init__ 接收,这是实际创建的内容。您能做的最好的事情是:

def __init__(self):
    self_template = super().with_two_legs('Human')
    # Cheaty way to copy all attributes from self_template to self, assuming no use
    # of __slots__
    vars(self).update(vars(self_template))

无法在 __init__ 中调用备用构造函数并让它隐式更改 self。关于我能想到的在不创建辅助方法并保留备用构造函数的情况下按照您的预期工作的唯一方法是使用 __new__ 而不是 __init__ (所以您可以返回由另一个构造函数创建的实例),并使用备用构造函数做一些糟糕的事情来显式调用顶级类的 __new__ 以避免循环调用依赖:

class Animal:
    def __new__(cls, name, legs):  # Use __new__ instead of __init__
        self = super().__new__(cls)  # Constructs base object
        self.legs = legs
        print(name)
        return self  # Returns initialized object
    @classmethod
    def with_two_legs(cls, name):
        # extremely long code to generate name_full from name
        name_full = name
        return Animal.__new__(cls, name_full, 2)  # Explicitly call Animal's __new__ using correct subclass

class Human(Animal):
    def __new__(cls):
        return super().with_two_legs('Human')  # Return result of alternate constructor

关于python - 在python中用父类方法覆盖__init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57366578/

相关文章:

python - 检查 *some* 用户是否存在于 Linux 或 Windows 中的可移植方法?

python - 用python重写部分c/c++程序

python - numpy数组的就地置换

c++ - 可以删除抽象类而不是子类吗?

Objective-C:实例变量超出调试器的范围

inheritance - 如何在 TypeScript 中扩展宿主对象(例如错误)

python - TypeError : unhashable type: 'TopicAndPartition' when KafkaUtils. createDirectStream 的原因是什么?

C++ 复制构造函数和默认构造函数

grails - 在Grails中是否有更好的设置关系的方法?

java - 为内部子接口(interface)创建 "default constructor"