dxbmozzarella
dxbmozzarella

Reputation: 21

How do I mutate/modify an instance attribute?

I want to distinguish the first time I initiate a class from all the other times I initiate it. I've created an instance attribute and set its value to True. What do I do for all subsequent instances to have that attribute value as False?

class Cool(Dude): 

    def __init__(self):
        self.coolnesscheck = True

Upvotes: 2

Views: 146

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can use a class attribute, to indicate if the first object has been created or not. Example -

class Cool:
    __firstinit = True

    def __init__(self):
        self.coolnesscheck = Cool.__firstinit
        Cool.__firstinit = False

I am prepending __ in the name to introduce Name Mangling , so that the attribute is not easily accessible outside the class.

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

Use a class attribute, and set it to False when you instantiate an object of that class:

>>> class Cool:
...     coolnesscheck = True
...     def __init__(self):
...         self.coolnesscheck = Cool.coolnesscheck
...         Cool.coolnesscheck = False
...
>>> Cool.coolnesscheck
True
>>> a = Cool()
>>> Cool.coolnesscheck
False
>>> a.coolnesscheck
True
>>> b = Cool()
>>> Cool.coolnesscheck
False
>>> b.coolnesscheck
False

Upvotes: 0

Related Questions