David542
David542

Reputation: 110083

Setting class variable

I have noticed the following in setting a class variable:

from ingest.models import WBReport
wb=WBReport()
wb.date = '2019-01-09'

The above does not set the date for the class. For example, calling this method, it prints None:

@classmethod
def load_asin(cls):
    print cls.date

However, if I add another method to set that variable it does work. For example:

@classmethod
def set_date(cls, date):
    cls.date=date

from ingest.models import WBReport
wb=WBReport()
wb.set_date('2019-01-09')

Why does the first method (wb.date=X)not work but the second one (wb.set_date(X)) does?

Upvotes: 0

Views: 43

Answers (1)

chepner
chepner

Reputation: 530970

Instance variables and class variables exist separately. wb.date = '2019-01-09' sets an instance variable on the object wb, not the class variable WBReport.date, which is what the class method set_date sets.

The call to the class method is roughly equivalent to WBReport.date = '2019-01-09'.

Upvotes: 4

Related Questions