Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python添加和获取魔法(dunder)方法_Python_Python 3.x_Math_Magic Methods - Fatal编程技术网

Python添加和获取魔法(dunder)方法

Python添加和获取魔法(dunder)方法,python,python-3.x,math,magic-methods,Python,Python 3.x,Math,Magic Methods,我遇到了一个关于Python dunder方法的问题。有一个表示数字的类,但是我想对表示的数字的算术进行一些限制。因此,我有以下几点: class Property: def __init__(self, value): self.value = value def __get__(self, instance, owner): return instance.value def __set__(self, instance, value)

我遇到了一个关于Python dunder方法的问题。有一个表示数字的类,但是我想对表示的数字的算术进行一些限制。因此,我有以下几点:

class Property:
    def __init__(self, value):
        self.value = value
    def __get__(self, instance, owner):
        return instance.value
    def __set__(self, instance, value):
        # Implement some arithmetic boundaries
        instance.value
    def __add__(self, other):
        # Implement arithmetic boundaries
        self.value += other
    def __sub__(self, other):
        etc..
现在这行不通了。如果我创建了一个实例并尝试向该值添加如下内容:

p = Property(0)
p + 5
p = 6

p将不再是property类型,而是int。我想合并所有这些dunder方法。但是这似乎是不可能的。

要添加到位,我相信您希望实现支持
+=
的方法,例如
\uu iadd\uu()
。不客气=)@AthylusI无法重现您描述的问题。当我运行您在示例中显示的精确代码时,我看到
p.value
等于5。我怀疑您实际上在做其他事情,在简化示例代码的过程中,您已经编辑掉了遇到的问题。是的@布莱克特是对的。代码将按您拥有的方式工作。但是,使用+=(
\uu iadd\uu()
)操作符实现就地操作更符合预期行为。对于常规的
\uuuu add\uuuu()
操作,您应该返回另一个属性对象,其值设置为5,例如。谢谢@Todd。但是,我仍然不能这样设置变量。让我更新我的问题。还可以使用iadd和p+=1将其设置为无?您可以发布处理该对象的代码吗?我注意到在
\uuuu set\uuuu()
方法中,没有设置变量。您只有
实例。value
您的代码适用于我和其他海报,因此这没有意义。要添加到适当的位置,我相信您希望实现支持
+=
的方法,例如
\u iadd\u()
。不客气=)@AthylusI无法重现您描述的问题。当我运行您在示例中显示的精确代码时,我看到
p.value
等于5。我怀疑您实际上在做其他事情,在简化示例代码的过程中,您已经编辑掉了遇到的问题。是的@布莱克特是对的。代码将按您拥有的方式工作。但是,使用+=(
\uu iadd\uu()
)操作符实现就地操作更符合预期行为。对于常规的
\uuuu add\uuuu()
操作,您应该返回另一个属性对象,其值设置为5,例如。谢谢@Todd。但是,我仍然不能这样设置变量。让我更新我的问题。还可以使用iadd和p+=1将其设置为无?您可以发布处理该对象的代码吗?我注意到在
\uuuu set\uuuu()
方法中,没有设置变量。您只有
instance.value
您的代码适用于我和其他海报,因此这没有意义。