尽管没有使用全局和正确的赋值

时间:2017-08-22 09:12:22

标签: python

我通常不会在python中编码。我有类方法get_review,它接受评论ID并从db返回评论。我没有全局变量,首先分配变量然后引用它。

这是该方法的代码。

class review:

    def __init__(self, db, id_=None, product_id=None, rating = None, user_id = None, comment = None ):
        self.db = db

        if id_ is None:
            if not isinstance(rating, (long, int)) and (rating > 5 or rating < 0) : 
                raise Exception(notifs.errors.invalid_rating)

            self.product = product(db, product_id)
            self.rating = rating
            self.user_id = user_id
            self.comment = comment
        elif id_ is not None:
            r = self.get_review(id_)
            if r is not False:
                self.product = product(db, r[0])
                self.user_id = r[1]
                self.rating = r[2] 
                self.comment = r[3]
                self.id = id_
            else:
                raise Exception(notifs.errors.invalid_arguments)

    def get_review(self, id_):
        query = """SELECT * FROM review where id = ? """

        rv = self.db.select(query, [id_])
        if (not rv):
            return False
        else:
            return rv.pop()

    def set_review(self):
        query = """INSERT INTO review(pid, uid, rating, comment) VALUES (?,?,?,?)"""

        params = [self.product.id, self.user_id, self.rating, self.comment]
        review_id = self.db.insert(query, params)
        if (review_id is False):
            raise Exception(notifs.errors.invalid_review)
        self.id = review_id

我得到的错误是:

if (not rv): NameError: global name 'rv' is not defined

1 个答案:

答案 0 :(得分:0)

创建MCVE时问题已解决。代码本身没有任何问题,问题是混合制表符和空格缩进,它使get_review方法超出了类review的范围

经验教训:在向SO发布问题之前始终创建MCVE。