3sm1r
3sm1r

Reputation: 530

A method that temporarily changes the attribute of an instance

I want to define a method that updates some of the attributes in an instance of a given class, then it checks some properties after the update. However, after this checking procedure, I want the attributes to go back to their initial value, since the update was only needed for the checking. I will try to clarify what I mean with an example.


class Cl:
    def __init__(self,number):
        self.number=number
    def checking(self):
        self.number+=1
        if self.number<8:
            return True
        else:
            return False

in this way, whenever I use the checking method, the attribute will be updated forever, rather than just during the checking:

I1=Cl(6)
print I1.number
print I1.checking()
print I1.number

The last print will return 7. How can I make the update in such a way that the attribute does not change permanently?

(Of course, while in this simple example I could just add self.number-=1 inside the if, I do not want to do that, because when I will use a less trivial update, the inverse operation might not be straightforward)

Upvotes: 0

Views: 212

Answers (1)

Samwise
Samwise

Reputation: 71454

Ideally, you just wouldn't change the attribute at all:

class Cl:
    def __init__(self, number):
        self.number = number
    def checking(self):
        if self.number + 1 < 8:
            return True
        else:
            return False

In a more complex example you might use a local variable, e.g.:

class Cl:
    def __init__(self, number):
        self.number = number
    def checking(self):
        number = self.number
        number += 1
        if number < 8:
            return True
        else:
            return False

Upvotes: 4

Related Questions