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?

asked Jan 9, 2019 at 20:04
1

1 Answer 1

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

answered Jan 9, 2019 at 20:09
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. Why then is it possible to run the classmethod method from the Instance? Do all instances have access to all staticmethods/classmethods?
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.