Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从父类实例化子类而不更改父代码_Python_Class_Inheritance_Instantiation - Fatal编程技术网

Python 从父类实例化子类而不更改父代码

Python 从父类实例化子类而不更改父代码,python,class,inheritance,instantiation,Python,Class,Inheritance,Instantiation,首先,这里是我的(伪)代码: somemodule.py: othermodule.py 问题是,我想对父类进行monkey-patch,因此它将调用childclass的构造函数,而不更改somemodule.py的代码。 无论是仅在类实例中(舒尔更好)还是在全球范围内进行修补,这都无关紧要 我知道我可以重写某个函数,但它包含太多的代码行,因为这是合理的 谢谢您可以使用: class childclass(parentclass): def somefunction(self):

首先,这里是我的(伪)代码:

somemodule.py:

othermodule.py

问题是,我想对父类进行monkey-patch,因此它将调用childclass的构造函数,而不更改somemodule.py的代码。 无论是仅在类实例中(舒尔更好)还是在全球范围内进行修补,这都无关紧要

我知道我可以重写某个函数,但它包含太多的代码行,因为这是合理的

谢谢

您可以使用:

class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()
您可以为此使用:

class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()

您希望所有构造
父类的尝试都改为构造
子类
,或者只在
父类
中进行尝试,或者只在
父类中进行此特定尝试。somefunction
,或者后两者之一,但仅当
self
子类
时才进行此操作,所以我会很感激任何一种回答,但最好是在家长课堂上尝试。事实上,这可能是最困难的可能性。但让我想想……我在中讨论了这一点,尽管它取代了
parentclass()
的所有出现。我可以想到两个可能会起作用的骇人听闻的事情:(1)用一个包装器替换
parentclass
的每个方法,该包装器修补
\uuuuuuu new\uuuuuuuu
,调用原始方法,并还原
\uuuuuuu new\ucode>。(2) 将
parentclass
的每个方法替换为在修改的
globals
中运行原始方法的包装器,其中
parentclass
已替换为
childclass
。但我认为这两种方法都不够好,不值得编写代码。您希望所有构造
父类的尝试都改为构造
子类
,或者只在
父类
中进行尝试,或者只在
父类中进行此特定尝试。somefunction
,或者是后两者中的一个,但只有当
self
childclass
的时候?好吧,所有这些,我都会很感激你的回答,但最好是在parentclass中尝试。实际上,这可能是最困难的可能性。但让我想想……我在中讨论了这一点,尽管它取代了
parentclass()
的所有出现。我可以想到两个可能会起作用的骇人听闻的事情:(1)用一个包装器替换
parentclass
的每个方法,该包装器修补
\uuuuuuu new\uuuuuuuu
,调用原始方法,并还原
\uuuuuuu new\ucode>。(2) 将
parentclass
的每个方法替换为在修改的
globals
中运行原始方法的包装器,其中
parentclass
已替换为
childclass
。但我认为这两种方法都不够好,都不值得编码。这是一种很好的干净方法,可以完成我的“骇人听闻的黑客行为(1)”。在我的情况下,它不起作用,因为parentclass最终是其他类的子类,parentclass的父类新方法被调用,它创建parentclass,而不是所谓的修补子类,将尝试找到如何管理它。@offlinehacker您也可以修补
\uuuuu新的\uuuuu
方法。另外,阅读.@LauritzV.Thaulow可能会有所帮助。最终,它像一个魔咒一样,修补了顶级的
\uuuuuu new\uuuuu
。这个很难。谢谢一个很好的干净的方法来做我的“骇人听闻的事情(1)”。嗯,在我的例子中它不起作用,因为parentclass最终是另一个类的子类,parentclass的父类新方法被调用,它创建了parentclass,而不是所谓的修补子类,将尝试找到如何管理它。@offlinehacker您也可以修补
\uuuuu新的\uuuuu
方法。另外,阅读.@LauritzV.Thaulow可能会有所帮助。最终,它像一个魔咒一样,修补了顶级的
\uuuuuu new\uuuuu
。这个很难。谢谢
class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()