在Python3中用元类重新定义

2024-10-01 00:16:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python3学习元编程。我的教授给了我们这个练习:

编写在向导中转换Student实例的元类拼写。

我这样做了:

class Spell(type):
    def __new__(cls, classname, supers, cls_dict):
        cls_dict['__init__'] = Spell.toWizard()
        cls_dict['__qualname__'] = 'wizard'
        return type.__new__(cls, 'wizard', supers, cls_dict)

    @staticmethod
    def toWizard():
        def init(*args):
            wizard(args, 'fire_spell')
        return init    

class student(metaclass=Spell):
    def __init__(self, name):
        self.name = name

class person():
    def __init__(self, name):
        self.name = name

class wizard(person):
    def __init__(self, name, magic):
        self.magic = magic
        super().__init__(name)



if __name__ == '__main__':
    s = student('name1')
    print(s.__dict__)
    s = student('name2')
    print(s.__dict__)

正确地调用了向导类__init__,而不是学生类__init__,但是创建的对象有一个空的__dict__。我哪里出错了?在


Tags: nameselfnewinitdeftypemagicstudent
1条回答
网友
1楼 · 发布于 2024-10-01 00:16:35

您的init()替换函数创建一个本地wizard()实例,并且不返回任何内容:

def init(*args):
    wizard(args, 'fire_spell')

这是一个单独的实例,self没有被触及。在

不要使用生成新类的__new__。您只重命名了student类,并给了它一个无效的__init__方法。在

重写__call__方法以钩住创建实例。在这里,您可以替换或忽略第一个参数,即student类对象,并使用wizard类来代替它:

^{pr2}$

因为student通常只接受一个参数,所以如果没有指定参数,上面的内容会添加一个magic参数。在

演示:

>>> student('name1')
<__main__.wizard object at 0x10f1e8198>
>>> vars(_)
{'magic': 'fire_spell', 'name': 'name1'}

相关问题 更多 >