0

Possible Duplicate:
Why do you need explicitly have the “self” argument into a Python method?

In Python, instance variables must be accessed via self.x, but global variables can be read by just writing x. How come?

Community
  • 1
  • 1
Casebash
  • 114,675
  • 90
  • 247
  • 350
  • @djechlin: It's not quite the same question. Why not follow the same principal for global variables too? – Casebash Dec 12 '12 at 23:40

1 Answers1

1

This is a frequently asked question, but essentially: it is so as to avoid name conflicts or confusion about which of instance or global variables are being accessed.

The philosophy is "Explicit is better than implicit".

Andrew Gorcester
  • 19,595
  • 7
  • 57
  • 73
  • 1
    Then why not follow the same principal for global variables too? – Casebash Dec 12 '12 at 23:40
  • 2
    If the problem is possible confusion/name shadowing between instance and global variables, then changing the naming convention for one of those to be explicit solves the problem. And while "global variables" are uncommon in Python as such, imported modules etc. are also in the global namespace and are used more commonly than anything else in Python, so an inconvenient convention for calling things in the global namespace would be more of a pain than the same for calling things in the instance variable namespace. – Andrew Gorcester Dec 12 '12 at 23:46