Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a class attribute inside __init__?

class Ant:
    count = 0

    def __init__(self):
        if count == 0:
            self.real = True
        else:
            self.real = False
        count += 1

So basically what I want to achieve is I want only the first instance of this class to have the "real" attribute to be True, and the subsequent attributes to be False. I know right now this is going to give me unboundlocal error for count. How do I make this work?

like image 465
iswg Avatar asked Jan 04 '23 14:01

iswg


1 Answers

Change count ToAnt.count

As count is a class member (shared between all instances of Ant class) and does not belong to a specific instance you should use it with the prefix of the class name.

class Ant:
    count = 0

    def __init__(self):
        if Ant.count == 0:
            self.real = True
        else:
            self.real = False
        Ant.count += 1
like image 180
omri_saadon Avatar answered Jan 18 '23 23:01

omri_saadon