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

Terry Reedy tjreedy at udel.edu
Sun Dec 11 19:51:05 EST 2016


On 12/11/2016 5:29 PM, Gregory Ewing wrote:
> 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?

Yes. Use the form appropriate to the situation.  In other words, use 
open-eyed rule, not a closed-eye rule.  This applies to much of Python 
programming and programming is general.  Greg nicely explains the 
application of this rule.

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

The use of a (constant) class attribute as default instance attribute 
might be an optimization added after the first version of the class, or 
one that could disappear in the future.

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

I agree with the other post suggesting using 'next_serial' as the class 
attribute, as that is what the class attribute is.  I would access it as 
Box.serial.

Instance methods should normal be accessed through an instance, though 
there are exceptions.

-- 
Terry Jan Reedy



More information about the Python-list mailing list