1

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.

RedCraig
  • 493
  • 4
  • 14

1 Answers1

0
class Baz(Foo):
  class_attribute = "Hello, World!"

Baz().bar()

And now they have completely different behavior. Program for results, not for efficiency.

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
  • So there's only a difference when inheriting? If not inheriting (considering Foo class in isolation), is there any difference other than personal preference / code readability? Good example btw, implications for inheritance had not occurred to me. – RedCraig Jun 16 '16 at 22:52