本文介绍了Python 3 超级和元编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式复制然后修改一个类,但是我遇到了 python 3 的魔术超级问题,例如以下

I'm trying to duplicate and then modify a class programmatically but I'm running into problems with python 3's magic super for example the following

class Base():
    def __init__(self):
        print("Base init")

class Orginal(Base):
    def __init__(self):
        super().__init__()
        print("Orginal init")

Modified = type(Orginal.__name__, Orginal.__bases__, dict(Orginal.__dict__))
Modified.f = lambda self: print("f")

m = Modified()

加注

TypeError: super(type, obj): obj must be an instance or subtype of type

TypeError: super(type, obj): obj must be an instance or subtype of type

所以我想知道,有什么办法可以帮助 super() 在通过 type() 创建的类中找到正确的 __class__ 单元格吗?

So I'm wondering, is there someway I can help super() find the right __class__ cell in a class created through type()?

推荐答案

这个答案,看来你不能用deepcopy来复制类,并且假设您在 Original.__init__ 方法中有 super() 调用,ModifiedOriginal 的子类> (除非您在复制"后还修改了 Modified 类中的 __init__ 方法).

Looking at this answer, it appears that you cannot use deepcopy to copy classes, and given that you have that super() call in your Original.__init__ method, Modified be a subclass of Original (unless you also modify the __init__ method in your Modified class after it's been "copied").

这篇关于Python 3 超级和元编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 16:27