首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在生成器中访问Python类@属性

在生成器中访问Python类@属性
EN

Stack Overflow用户
提问于 2016-01-14 10:29:01
回答 1查看 307关注 0票数 0

这是我的CurrencyLot课程:

代码语言:javascript
复制
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

我的金额为“私有”变量,并使用@property访问它。此函数正在抛出错误:

代码语言:javascript
复制
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:‘生成器’对象没有属性‘has’。

有什么方法可以做到吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-14 10:33:45

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

代码语言:javascript
复制
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)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34787174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档