访问gen中的Python class@property

2024-10-16 20:41:06 发布

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

这是我的CurrencyLot课程:

class CurrencyLot(models.Model):
    _amount = models.IntegerField(default=0)
    expiry_date = models.DateTimeField(null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    is_expired = models.BooleanField(default=False)
    _usage_count = models.IntegerField(default=1)

    class Meta:
        ordering = ['expiry_date',]

    @property
    def amount(self):
        if self._usage_count < 1 or self.is_expired:
            return 0
        else:
            return self._amount

    @property
    def usage_count(self):
        return self._usage_count

    def set_amount(self, amount):
        self._amount = amount
        self.save()
        return self._amount

我将amount作为“private”变量,并使用@property访问它。 此函数引发错误:

def deduct_amount(self, deduction):
        deduction = int(deduction)
        currency_lots_iterator = self.currency_lots.filter(is_expired=False).iterator()
        while deduction > 0:
            if deduction > currency_lots_iterator.amount:
                deduction -= currency_lots_iterator.amount
                currency_lots_iterator.set_amount(0)
                currency_lots_iterator.next()
            elif deduction == currency_lots_iterator.amount:
                deduction = 0
                currency_lots_iterator.set_amount(0)
            elif deduction < currency_lots_iterator.amount:
                deduction = 0
                currency_lots_iterator.set_amount(currency_lots_iterator.amount-deduction)
        return self.total_valid_amount()

错误为:AttributeError:“generator”对象没有属性“amount”。你知道吗

有办法做到这一点吗?你知道吗


Tags: selftruedefaultdatereturnmodelsdefcount
1条回答
网友
1楼 · 发布于 2024-10-16 20:41:06

您的currency_lots_iterator是一个生成器(从查询集中迭代对象)-您必须从中获取下一个项,并从中访问:

currency_lots_iterator = self.currency_lots.filter(is_expired=False).iterator()
while deduction > 0:
    currency_lot = currency_lots_iterator.next()

然后使用currency_lot.amountcurrency_lot.set_amount(x)

相关问题 更多 >