The right way to 'call' a class attribute inside the same class

Gregory Ewing greg.ewing at canterbury.ac.nz
Sun Dec 11 17:29:19 EST 2016


Juan C. wrote:
> The instructor said that the right way to call a class attribute is to use
> 'Class.class_attr' notation, but on the web I found examples where people
> used 'self.class_attr' to call class attributes. I believe that using the
> first notation is better ('Class.class_attr'), this way the code is more
> explicit, but is there any rules regarding it?

It depends on how the class attribute is being used.

If you're only reading the attribute, either way will work.
Which one is more appropriate depends on what the attribute
is used for. Often a class attribute is used as a default
value for an instance attribute, in which case accessing it
via the instance is entirely appropriate. On the other
hand, if it's truly mean to be an attribute of the class
itself, accessing it via the class is probably clearer.

If the attribute is being written, you don't have any
choice. If you want to rebind the attribute in the class,
you have to access it via the class. This is the case
for this line in your example:

         Box.serial += 1

If instead you did 'self.serial += 1' it would create
a new instance attribute shadowing the class attribute,
and the class attribute would remain bound to its
previous value.

-- 
Greg


More information about the Python-list mailing list