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

Chris Angelico rosuav at gmail.com
Sun Dec 11 17:26:41 EST 2016


On Mon, Dec 12, 2016 at 7:10 AM, Juan C. <juan0christian at gmail.com> wrote:
> class Box:
>     serial = 100
>
>     def __init__(self, from_addr, to_addr):
>         self.from_addr = from_addr
>         self.to_addr = to_addr
>         self.serial = Box.serial
>         Box.serial += 1
>

I would say that this is awkward usage; the class attribute isn't
being used as a default for the instance, it's being used as "the next
one". I would rename the class attribute to "next_serial". That would
give you the freedom to use whichever notation you like, as there
won't be a conflict.

ChrisA


More information about the Python-list mailing list