如何在没有类的情况下覆盖当前脚本的魔术方法? [英] How to override a magic method for the current script without a class?

查看:85
本文介绍了如何在没有类的情况下覆盖当前脚本的魔术方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为当前脚本覆盖魔术方法?

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

例如,在上面,我希望对b的赋值可以调用__setattr__,但不会.我想念什么?

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

推荐答案

__setattr__ 适用于形式为a.b = c的赋值,该形式转换为type(a).__setattr__(b, c).简单的名称分配是语言本身的基本操作,没有任何魔术方法可以实现.

__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.

您只是在定义一个名为__setattr__的模块级函数,而不是任何特定类的魔术方法.

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

这篇关于如何在没有类的情况下覆盖当前脚本的魔术方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆