[Tutor] OOP and Python.. a gentle remark
Alan Gauld
alan.gauld at btinternet.com
Wed Oct 25 21:23:49 CEST 2006
"Asrarahmed Kadri" <ajkadri at googlemail.com> wrote
> Why is it necessary to explicity use self argument in the class
> functions
Because Guido made it that way. :-)
But he did it for good reasons which others have pointed out already.
Although languages like C++ and Java use implicit object references,
you can make them explicit with the 'this' keyword and most industrial
coding standards mandate that 'this' be used when referencing class
level variables inside methods. As in so many things Python simply
takes best practice and makes it mandatory.
> the function? Isnt it ? (the use of 'self' keyword really confuses
> me. and
If its the actual term 'self' then you can change it to anything
you prefer. C++/Java programmers might prefer 'this', some
others have used 'my':
class C:
def __init__(my, aValue):
my.value = aValue
is perfectly valid Python.
> to make matter worse the variables can be accessed from outside teh
> class.
> Isnt it a violation of the OOP principle of ENCAPSULATION)
The original OOP concept of encapsulation refers to the ability
to bind functions and data together in a single unit - a class or
object - and had nothing to do with data hiding which is the ability
to conceal the implementation details behind an API.
It was only after C++ came out with its gazillion access
controls (public, private, protected, friend etc) that people started
to confuse data hiding and encapsulation. Many early OOP
languages (most Lisps included) do not offer explicit or strict
data hiding.
> Also please let me know hwo can we declare
> PRIVATE VARIABLES in Python...??
Why do you think you need them?
Do you frequently hit bugs because you couldn't resist the
urge to access members directly? While there can be problems
with badly behaved programmers on large projects, in the
things Python is typically used for its very rarely a problem.
And it can add significantly to the complexity of the code
when you try to derive a class from one with private data.
Very few designers are sufficiently ppsychic to predict
exactly how all future users will want to modify their class!
The result is they supply get/set methods for all data which
are simply pass through methods. In doing so they
completely annull any benefit of private members and
introduce potential performance problems.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list