(no subject)

Steve Holden sholden at bellatlantic.net
Mon Feb 28 14:30:34 EST 2000


Gregoire Welraeds wrote:
> 
> This question is related to OOP approach.
> Why do I have to :
>         def __init__(self, name):
>                 self.__name = name
> 
The self argument provdes the necessary object instance context for
retrieval of the required instance variable. Class methods are
special functions, in that the instance references are silently
provided as an extra first argument.

>         def getname(self):
>                 return self.__name
> and
> x= MyObject.getname()
> 
Yes, this all seems to work nicely.

> instead of
>         def __init__(self, name):
>                 name= name

Here you will run up against the three-scopes rule: the name on the LHS
of the assignment will be a variable local to the method, and thus not
available after the __init__ method completes.

> and then
> x= MyObject.name
> 
There's nothing Pythonically wrong with using instance variables this way.
Using get/set routines gives better decoupling and allows you to change
your objects' implementations without breaking surrounding code.  So there
is nothing *technically* wrong with:

>>> class Foo:
	def __init__(self):
		self.localvar = 177
		
		
>>> bar = Foo()
>>> bar.localvar
177
>>> 

It's just a question of whether you want to allow consumers of object
services to "reach behind" the interfaces in this way.  In this respect
Python is much more relaxed than Java or C++, which enforce restrictions
on attribute accessibility.  In a typeless language it's more appropriate
to leave it to the programmer's discretion.

> --
> Life is not fair
> But the root password helps
> --
> 
> Gregoire Welraeds

Python makes it easy to write good programs rather than difficult to
write bad ones.

regards
 Steve
--
"If computing ever stops being fun, I'll stop doing it"



More information about the Python-list mailing list