如何捕获特定的名称分配? [英] How to catch a particular name assignment?

查看:45
本文介绍了如何捕获特定的名称分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(基于此问题):

在设置对象的attribute时,可以覆盖对象的__setattr__魔术方法以具有其他指令.如:

One can override the __setattr__ magic method for an object to have additional instructions when an attribute of an object is set. As in:

class MyClass(object):
    def __init__(self, attribute=None):
        object.__init__(self)
        self.attribute = attribute


    def __setattr__(self, name, value):
        self.__dict__[name] = value
        if name == 'attribute':
            print("attribute's value is modified to {}.".format(
                                                        self.attribute))


if __name__ == '__main__':
    my_obj = MyClass(True)
    while True:
        my_obj.attribute = input()

  • 如何在当前脚本中捕获特定的名称分配 无需使用类(特别是调用具有更多内容的方法 说明)?
    • How can I catch a particular name assignment in the current script without using classes(specifically to call a method with more instructions)?
    •  

      def b_is_modified():
          print("b is modified!")
      
      
      if __name__ == '__main__':
          a = 3
          b = 4
          b = 5
      

      b分配值时如何调用b_is_modified?

      推荐答案

      基于此答案:

      不能 被捕获(至少在python级别).

      It can't be catched(at least in python level).

      简单名称分配(b = 4)是语言本身的基础操作.它不是根据可以覆盖的较低级别的操作来实现的.只是.

      Simple name assignment(b = 4), as oppposed to object attribute assignment (object.b = 5), is a fundamental operation of the language itself. It's not implemented in terms of a lower-level operation that one can override. Assignment just is.

      这篇关于如何捕获特定的名称分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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