[Tutor] OOP and Python.. a gentle remark

Andrei project5 at redrival.net
Wed Oct 25 13:13:32 CEST 2006


Asrarahmed Kadri <ajkadri <at> googlemail.com> writes:

> the use of 'self' keyword really confuses me. 

I see how it can annoy you, but not how it can *confuse* you - if anything,
"self" removes any confusion about whether you're looking at a local variable or
an object property. By the way, the use of special identifiers is not uncommon
in dynamic languages. Ruby for example uses the prefixes @, @@ and $ to define
variable scope (which are not particularly self-explanatory - I think they're
class, instance and global vars) and keywords (private, protected, public) to
define method visibility. 

> and to make matter worse the variables can be accessed from outside teh class. 
> Isnt it a violation of the OOP principle of ENCAPSULATION)

Python has conventions for this: prepend _ for protected and __ for private
(private names get mangled). In an interactive session:

  >>> class a(object):
  ...     def _protected(s): # don't *have* to use "self" :)
  ...         print s
  ...     def __private(s):
  ...         print "private"
  >>> A = a()
  >>> A._protected()
  <__main__.a object at 0x00AF2E10>
  >>> A.__private()
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'a' object has no attribute '__private'

Lets's examine what's happened:

  >>> dir(A) 
  [<snip>, '_a__private', '_protected']

See, __private was mangled to _a__private. We can still access it of course:

  >>> A._a__private()
  private

Python approaches the programmer as a responsible person: if I see a method name
is mangled (or marked with _), I know I'm not supposed to use it - but can use
it if I really need to (and suffer the consequences if the next version of the
class breaks my code). 
Other languages choose the opposite approach: private is private, don't trust
the programmer, tough luck if you really really need access to that private.
Unfortunately you will invariably encounter cases when you need to access
privates and these are major PITA's. Usually you can get your hands on the
secret stuff, it's just very annoying and silly (e.g. by creating shadow classes
or other workarounds).

In the end it comes down to a choice between making some unavoidable cases very
cumbersome to deal with, or trusting the programmer to do the right thing -
thereby making it easier to stick his grubby little fingers in places where he
shouldn't. Some people prefer the former, some the latter.

Yours,

Andrei



More information about the Tutor mailing list