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

2024-06-09 07:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个关于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方法。但这似乎是不可能的


Tags: 方法instanceselfinitvaluedef数字property