微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用装饰器防止构造函数被覆盖

如何解决使用装饰器防止构造函数被覆盖

def no_override(const):
    def wrapper(self):
        super().__init__(self)
        const()
    return wrapper

class Hello:
    def __init__(self):
        print('hey there')
        print('my name is')
        print('hello')
        self.a = 10

class World(Hello):
    @no_override
    def __init__(self):
        print('and this is')
        print('the other constructor')
        self.b = 20

代替写作

super().__init__(self)

在派生类的构造函数中,我一直都想制作一个@no_override装饰器来为我做这件事。 但是,我无法使其访问超类。

>>> w = World()
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
  File "deco_overriding_prevent.py",line 5,in wrapper
    super().__init__(self)
RuntimeError: super(): __class__ cell not found
>>>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。