我在用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__
。我哪里出错了?在
您的
init()
替换函数创建一个本地wizard()
实例,并且不返回任何内容:这是一个单独的实例,
self
没有被触及。在不要使用生成新类的
__new__
。您只重命名了student
类,并给了它一个无效的__init__
方法。在重写
^{pr2}$__call__
方法以钩住创建实例。在这里,您可以替换或忽略第一个参数,即student
类对象,并使用wizard
类来代替它:因为
student
通常只接受一个参数,所以如果没有指定参数,上面的内容会添加一个magic
参数。在演示:
相关问题 更多 >
编程相关推荐