0

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?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    Possible duplicate of [What is the difference between class and instance variables?](https://stackoverflow.com/questions/8959097/what-is-the-difference-between-class-and-instance-variables) – glibdud Jan 09 '19 at 20:10

1 Answers1

4

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'.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • thanks. Why then is it possible to run the `classmethod` method from the Instance? Do all instances have access to all staticmethods/classmethods? – David542 Jan 09 '19 at 21:00
  • The look-up algorithm for all attributes starts with the instance's own attribute dictionary, then tries the class of which the object is an instance, then the classes in the object's MRO. Note that it is possible for an instance attribute to shadow a class attribute, so it's not always possible to access class attributes via an instance. – chepner Jan 09 '19 at 21:05