Raúl Chirinos
Raúl Chirinos

Reputation: 99

How to change class attributes using a method?

I have a Django model class who has some default attributes, and I want to change the value of the complete variable by calling a function:

class Foo:
    complete = False

    def set_complete_true():
        complete = True

But after calling set_complete_true() the complete variable is still False.

Upvotes: 2

Views: 10566

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

An instance function (most functions are instance functions) has a special parameter that is always the first one called self. It is a reference to the object with which you call the function. For example, if you call some_instance.foo(), then foo is called with as self the some_instance.

You thus need to add the self parameter, and set the self.complete to True:

class Foo:
    complete = False

    def set_complete_true(self):
        self.complete = True

Upvotes: 4

Ali Yılmaz
Ali Yılmaz

Reputation: 1695

I believe this is worth a shot:

class Foo:
    complete = False

    def set_complete_true(self):
        self.complete = True

a = Foo()
a.set_complete_true()
print(a.complete) # should be True now

Upvotes: 1

Related Questions