The right way to 'call' a class attribute inside the same class
Juan C.
juan0christian at gmail.com
Sun Dec 11 15:10:56 EST 2016
I'm watching a Python course and was presented a topic regarding classes.
One of the examples were:
box.py
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
from box import *
a = Box('19 Beech Ave. Seattle, WA 98144', '49 Carpenter Street North
Brunswick, NJ 08902')
b = Box('68 N. Church Dr. Vicksburg, MS 39180', '8 Lake Forest Road
Princeton, NJ 08540')
print(a.serial) # print: 100
print(b.serial) # print: 101
print(Box.serial) # print: 102
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?
More information about the Python-list
mailing list