我遇到了一个关于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方法。但这似乎是不可能的
目前没有回答
相关问题 更多 >
编程相关推荐