When accessing class attributes, what is the difference when using the class name Foo
or self
within that classes methods?
>>> class Foo(object):
... class_attribute = "Oh Hai"
... def bar(self):
... print(Foo.class_attribute)
... print(self.class_attribute)
...
>>> Foo().bar()
Oh Hai
Oh Hai
Both work. In both cases I assume Python looks at the instance of the class and doesn't find the class attributes bound to it so then it proceeds to check the class attributes and find class_attribute
.
Is one more efficient than the other?
Is it just a personal preference for code readability? To me seeing ClassName.class_attribute
used within that class looks odd.