本文介绍了是否可以重载 Python 赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么神奇的方法可以重载赋值运算符,比如__assign__(self, new_value)?

Is there a magic method that can overload the assignment operator, like __assign__(self, new_value)?

我想禁止一个实例的重新绑定:

I'd like to forbid a re-bind for an instance:

class Protect():
  def __assign__(self, value):
    raise Exception("This is an ex-parrot")

var = Protect()  # once assigned...
var = 1          # this should raise Exception()

有可能吗?是不是疯了?我应该吃药吗?

Is it possible? Is it insane? Should I be on medicine?

推荐答案

你描述的方式是绝对不可能的.给名字赋值是 Python 的一个基本特性,没有提供任何钩子来改变它的行为.

The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior.

但是,可以根据需要控制对类实例中成员的分配,方法是覆盖 .__setattr__().

However, assignment to a member in a class instance can be controlled as you want, by overriding .__setattr__().

class MyClass(object):
    def __init__(self, x):
        self.x = x
        self._locked = True
    def __setattr__(self, name, value):
        if self.__dict__.get("_locked", False) and name == "x":
            raise AttributeError("MyClass does not allow assignment to .x member")
        self.__dict__[name] = value

>>> m = MyClass(3)
>>> m.x
3
>>> m.x = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __setattr__
AttributeError: MyClass does not allow assignment to .x member

请注意,有一个成员变量 _locked 控制是否允许赋值.您可以解锁它以更新值.

Note that there is a member variable, _locked, that controls whether the assignment is permitted. You can unlock it to update the value.

这篇关于是否可以重载 Python 赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:03
查看更多