How to override a magic method for the current script without a class?

假装没事ソ 提交于 2019-12-13 08:37:00

问题


How to override a magic method for the current script?

def __setattr__(name, value):
    __dict__[name] = value
    print("asd")
    if name == 'b':
        print(__dict__[name])


if __name__ == '__main__':
    a = 3
    b = 4
    b = 5

In above, for example, I expect assignments to b to call __setattr__ but they don't. What am I missing?


回答1:


__setattr__ only applies to assignments of the form a.b = c, which translates to type(a).__setattr__(b, c). Simple name assignments are a fundamental operation of the language itself, not implemented by any magic method.

You are just defining a module level function named __setattr__, not a magic method of any particular class.



来源:https://stackoverflow.com/questions/48722144/how-to-override-a-magic-method-for-the-current-script-without-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!