数据卡拉塞的 Python 3 默认值不会与属性一起使用



为什么属性对我不起作用,当我不指定 procent 时,它会给我抛出一个异常(这可能是一个错误吗? 还是我在数据类中缺少的东西?

from dataclasses import dataclass, field
@dataclass
class A(object):
index: int
#procent: float = 1.0
procent: float = field(default=1.0)
def __post_init__(self):
self.row, self.col = divmod(self.index, 13)  # Row, Column
@dataclass
class B(object):
index: int
#procent: float = 1.0
procent: float = field(default=1.0)
def __post_init__(self):
self.row, self.col = divmod(self.index, 13)  # Row, Column
@property
def procent(self):
return self._procent
@procent.setter
def procent(self, x: float, base: float = 5):
self._procent = float(base * round(x * 100 / base) / 100)

print(A(index=1, procent=0.33))
# A(index=1, procent=0.33)
print(A(1))
# A(index=1, procent=1.0)
print(B(1, 0.33))
# B(index=1, procent=1.35)
B(1) # Explodes here
#    self._procent = float(base * round(x * 100 / base) / 100)
#TypeError: unsupported operand type(s) for *: 'property' and 'int'

由于您将值存储在self._procent中,因此还应将字段命名为_procent

_procent: float = field(default=1.0)

在完整示例的上下文中:

from dataclasses import dataclass, field
@dataclass
class B(object):
index: int
_procent: float = field(default=1.0)
def __post_init__(self):
self.row, self.col = divmod(self.index, 13)  # Row, Column
@property
def procent(self):
return self._procent
@procent.setter
def procent(self, x: float, base: float = 5):
self._procent = float(base * round(x * 100 / base) / 100)
print(B(1))

输出

B(index=1, _procent=1.0)

最新更新