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
  • 503
  • 1
  • 4
  • 15

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
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 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