user3441996
user3441996

Reputation:

setting an attribute at create retrieves None value - Python

So I have an Article class that models the articles in a store. When I create a new article, I want it to have an EAN 13 code. So I initialize the article with a 12 digits code and use the check_ean13() funtion to retrieve the control digit. It works but seems like in any moment, when the object is created, rewrite the ean13 attribute and replaces it for None. Any ideas?

Main

if __name__ == "__main__":

    # create article
    art1 = Article("123456789087", "Article 1", 145.6, 200.0)

    print art1
    print art1.get_ean13()

class Article

class Article:
    def __init__(self, cod, art_name, cost, listprice):
        self.ean13 = self.set_ean13(cod)
        self.art_name = art_name
        self.cost = cost
        self.listprice = listprice
        self.commission = None
        self.promotion=[]

    def get_ean13(self):
        return self.ean13

    def set_ean13(self,cod):
        cd = self.check_ean13(cod)
        ean13 = cod + str(cd)
        self.ean13=ean13

    def check_ean13(self, code):
        checksum = 0
        for i, digit in enumerate(reversed(code)):
            checksum += int(digit) * 3 if (i % 2 == 0) else int(digit)
        return (10 - (checksum % 10)) % 10

output:

None - Article 1 list price: 400.0
None

Upvotes: 0

Views: 18

Answers (1)

Kevin
Kevin

Reputation: 76244

self.ean13 = self.set_ean13(cod)

set_ean13 doesn't return anything, so you're effectively doing self.ean13 = None here. Just call the method without assigning the result.

self.set_ean13(cod)

Upvotes: 0

Related Questions