
April 10th, 2006, 03:35 PM
|
|
|
About classes and OOP in Python
Hello all,
I've been wondering a lot about why Python handles classes and OOP the
way it does. From what I understand, there is no concept of class
encapsulation in Python, i.e. no such thing as a private variable. Any
part of the code is allowed access to any variable in any class, and
even non-existant variables can be accessed: they are simply created.
I'm wondering what the philosophy behind this is, and if this
behaviour is going to change in any future release of Python.
It seems to me that it is difficult to use OOP to a wide extent in
Python code because these features of the language introduce many
inadvertant bugs. For example, if the programmer typos a variable name
in an assignment, the assignment will probably not do what the
programmer intended.
Ruby does something with this that I think would be excellent as an
inclusion in Python (with some syntax changes, of course). If private
variables require a setter/getter pair, we can shortcut that in some
way, i.e. (pseudocode):
class PythonClass:
private foo = "bar"
private var = 42
allow_readwrite( [ foo, var ] )
Or allow_read to only allow read-only access. Also there might be a
way to implement custom getters and setters for those times you want
to modify input or something:
class PythonClass:
def get foo():
return "bar"
def set var( value ):
var = value
Anyways, these are just some speculatory suggestions. My main question
is that of why Python chooses to use this type of OOP model and if it
is planned to change.
Thanks!
|

April 10th, 2006, 04:15 PM
|
|
|
Re: About classes and OOP in Python
You can do this in Python as well. Check out the property built-in
function. One can declare a property with a get, set, and delete
method. Here's a small example of a read-only property.
class Test(object):
def getProperty(self):
return 0;
prop = property(fget = getProperty)
t = Test()
print t.prop
t.prop = 100 # this will fail
|

April 10th, 2006, 04:45 PM
|
|
|
Re: About classes and OOP in Python
"fyhuang" <fyhuang@gmail.com> wrote:[color=blue]
> I've been wondering a lot about why Python handles classes and OOP the
> way it does. From what I understand, there is no concept of class
> encapsulation in Python, i.e. no such thing as a private variable. Any
> part of the code is allowed access to any variable in any class, and
> even non-existant variables can be accessed: they are simply created.
> I'm wondering what the philosophy behind this is, and if this
> behaviour is going to change in any future release of Python.[/color]
There are advantages and disadvantages to C++/Java style encapsulation
using private data. The advantages you (apparently) already know. The
disadvantage is added complexity. There's a saying, "You can't have a bug
in a line of code you never write". By having to write all those getter
and setter methods, you just add bulk and complexity.
That being said, you can indeed have private data in Python. Just prefix
your variable names with two underscores (i.e. __foo), and they effectively
become private. Yes, you can bypass this if you really want to, but then
again, you can bypass private in C++ too. You can also intercept any
attempt to access Python attributes by writing __getattr__() and
__setattr__() methods for your class.
[color=blue]
> It seems to me that it is difficult to use OOP to a wide extent in
> Python code because these features of the language introduce many
> inadvertant bugs. For example, if the programmer typos a variable name
> in an assignment, the assignment will probably not do what the
> programmer intended.[/color]
Yes, that is is a risk. Most people deal with that risk by doing a lot of
testing (which you should be doing anyway). If you really want to, you can
use the __slots__ technique to prevent this particular bug from happening
(although the purists will tell you that this is not what __slots__ was
designed for).
[color=blue]
> My main question is that of why Python chooses to use this type of OOP
> model and if it is planned to change.[/color]
It sounds like you are used to things like C++ and Java, which are very
static languages. Everything is declared at compile time, and there are
many safeguards in the language to keep you from shooting yourself in the
foot. They problem is, they often prevent you from getting any useful work
done either; you spend most of your time programming the language, not the
problem you are trying to solve.
In the past week, I've had two conversations with people about the nuances
of C++ assignment operators. None of our customers give two figs about
assignment operators. Getting them right is just a detour we need to take
to keep our software from crashing. With Python, I write a = b and trust
that it does the right thing. That lets me concentrate on adding value
that our customer will see.
|

April 10th, 2006, 05:15 PM
|
|
|
Re: About classes and OOP in Python
Em Seg, 2006-04-10 Ã*s 07:19 -0700, fyhuang escreveu:[color=blue]
> class PythonClass:
> private foo = "bar"
> private var = 42
> allow_readwrite( [ foo, var ] )[/color]
You are aware that foo and var would become class-variables, not
instance-variables, right?
But you can always do:
class PythonClass(object):
def __init__(self):
self.__foo = "bar"
foo = property(lambda self: self.__foo)
And then:
[color=blue][color=green][color=darkred]
>>> a = PythonClass()
>>> a.foo[/color][/color][/color]
'bar'[color=blue][color=green][color=darkred]
>>> a.foo = 'baz'[/color][/color][/color]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute
But you can also bypass this "security":
[color=blue][color=green][color=darkred]
>>> a._PythonClass__foo = 'baz'
>>> a.foo[/color][/color][/color]
'baz'
But this was not a mistake, nobody mistakenly writes "_PythonClass__".
[color=blue]
> Or allow_read to only allow read-only access. Also there might be a
> way to implement custom getters and setters for those times you want
> to modify input or something:
>
> class PythonClass:
> def get foo():
> return "bar"
>
> def set var( value ):
> var = value[/color]
There's a PEP somewhere that proposes things like (same example I gave
earlier):
class PythonClass(object):
def __init__(self):
self.__foo = "bar"
create property foo:
def get(self):
return self.__foo
--
Felipe.
|

April 10th, 2006, 05:15 PM
|
|
|
Re: About classes and OOP in Python
fyhuang <fyhuang@gmail.com> wrote:[color=blue]
> [ ... ] no such thing as a private variable. Any
>part of the code is allowed access to any variable in any class, and
>even non-existant variables can be accessed: they are simply created.[/color]
You're confusing two issues: encapsulation and dynamic name binding.
You might also want to check out the difference between read and
write access to non-existant variables.
[color=blue]
>I'm wondering what the philosophy behind this is,[/color]
"We are all consenting adults." And probably experience of data
encapsulation being more of a hinderence than a benefit.
[color=blue]
> and if this
>behaviour is going to change in any future release of Python.[/color]
I damn well hope not.
And if you want to control those writes, try this for a base class:
class restrict_set:
def __init__(self, allowed_names):
self._allowed_names = set(allowed_names)
def __setattr__(self, name, value):
if not name.startswith('_') and name not in self._allowed_names:
getattr(self, name)
self.__dict__[name] = value
(Someone else can do the new style class and the metaclass versions.)
--
\S -- siona@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
|

April 10th, 2006, 08:15 PM
|
|
|
Re: About classes and OOP in Python
Hi,
fyhuang schrieb:
[color=blue]
> I've been wondering a lot about why Python handles classes and OOP the
> way it does. From what I understand, there is no concept of class
> encapsulation in Python, i.e. no such thing as a private variable. Any[/color]
the answer is here:
http://tinyurl.com/obgho
--
Mit freundlichen Grüßen,
Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung
http://www.gregor-horvath.com
|

April 11th, 2006, 09:35 AM
|
|
|
Re: About classes and OOP in Python
fyhuang wrote:[color=blue]
> It seems to me that it is difficult to use OOP to a wide extent in
> Python code because these features of the language introduce many
> inadvertant bugs. For example, if the programmer typos a variable name
> in an assignment, the assignment will probably not do what the
> programmer intended.[/color]
You'll find that if you assign to a wrongly-typed variable name, then
later attempts to access the variable you wrongly believed you typed
will raise an exception. If you assign from a wrongly-typed variable,
again an exception will be raised.
I think it's important not to wrongly confuse 'OOP' with ''data hiding'
or any other aspect you may be familiar with from Java or C++. The
primary concept behind OOP is not buzzwords such as abstraction,
encapsulation, polymorphism, etc etc, but the fact that your program
consists of objects maintaining their own state, working together to
produce the required results, as opposed to the procedural method where
the program consists of functions that operate on a separate data set.
--
Ben Sizer
|

April 11th, 2006, 09:55 AM
|
|
|
Re: About classes and OOP in Python
Ben Sizer wrote:
[color=blue]
> I think it's important not to wrongly confuse 'OOP' with ''data hiding'
> or any other aspect you may be familiar with from Java or C++. The
> primary concept behind OOP is not buzzwords such as abstraction,
> encapsulation, polymorphism, etc etc, but the fact that your program
> consists of objects maintaining their own state, working together to
> produce the required results, as opposed to the procedural method where
> the program consists of functions that operate on a separate data set.[/color]
+1 QOTW
</F>
|

April 11th, 2006, 10:05 AM
|
|
|
Re: About classes and OOP in Python
Roy Smith wrote:
<snip>[color=blue]
> That being said, you can indeed have private data in Python. Just prefix
> your variable names with two underscores (i.e. __foo), and they effectively
> become private. Yes, you can bypass this if you really want to, but then
> again, you can bypass private in C++ too.[/color]
Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
on the contrary is a *protected* name ("touch me, touch me, don't worry
I am protected against inheritance!").
This is a common misconception, I made the error myself in the past.
Michele Simionato
|

April 11th, 2006, 10:25 AM
|
|
|
Re: About classes and OOP in Python
fyhuang wrote:[color=blue]
> Hello all,
>
> I've been wondering a lot about why Python handles classes and OOP the
> way it does. From what I understand, there is no concept of class
> encapsulation in Python, i.e. no such thing as a private variable.[/color]
Seems you're confusing encapsulation with data hiding.
[color=blue]
> Any
> part of the code is allowed access to any variable in any class,[/color]
This is also true for Java and C++ - it just a requires a little bit
more language-specific knowledge.
Python relies a lot on conventions. One of these conventions is that any
attribute whose name begins with an underscore is implementation detail
and *should* not be accessed from client code.
[color=blue]
> and
> even non-existant variables can be accessed:[/color]
Nope. You can dynamically *add* new attributes - either to an instance
or a class - but trying to *read* a non-existant attribute will raise an
AttributeError.
[color=blue]
> they are simply created.
> I'm wondering what the philosophy behind this is,[/color]
Dynamism.
[color=blue]
> and if this
> behaviour is going to change in any future release of Python.[/color]
Certainly not.
[color=blue]
> It seems to me that it is difficult to use OOP to a wide extent in
> Python code because these features of the language introduce many
> inadvertant bugs.[/color]
Don't assume, verify. My own experience is that it's *much more* easy to
do OOP with a dynamic language.
[color=blue]
> For example, if the programmer typos a variable name
> in an assignment, the assignment will probably not do what the
> programmer intended.[/color]
That's true for any language. I never had any serious problem with this
in 5+ years - not that I'm never making typos, but it never took me more
than a pair of minutes to spot and correct this kind of errors. OTOH,
Python's dynamism let me solved in a quick and clean way problems that
would have been a royal PITA in some less agile languages.
[color=blue]
> Ruby does something with this that I think would be excellent as an
> inclusion in Python (with some syntax changes, of course). If private
> variables require a setter/getter pair, we can shortcut that in some
> way, i.e. (pseudocode):
>
> class PythonClass:
> private foo = "bar"
> private var = 42
> allow_readwrite( [ foo, var ] )[/color]
A first point: in Ruby (which closely follows Smalltalk's model),
there's a definitive distinction between callable and non-callable
attributes, and this last category is *always* private.
A second point is that Python also provides you getter/setter for
attributes. The default is read/write, but you can easily make any
attribute read-only (or write-only FWIW) and add any computation.
[color=blue]
> Or allow_read to only allow read-only access. Also there might be a
> way to implement custom getters and setters for those times you want
> to modify input or something:
>
> class PythonClass:
> def get foo():
> return "bar"
>
> def set var( value ):
> var = value[/color]
What you want is named "property".
[color=blue]
> Anyways, these are just some speculatory suggestions.[/color]
Don't waste time with speculations. Read the Fine Manual instead, and
actually *use* Python.
[color=blue]
> My main question
> is that of why Python chooses to use this type of OOP model and if it
> is planned to change.[/color]
I'm not the BDFL, but my bet is that this will *not* change.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
|

April 11th, 2006, 10:25 AM
|
|
|
Re: About classes and OOP in Python
Roy Smith wrote:
(snip)
[color=blue]
> That being said, you can indeed have private data in Python. Just prefix
> your variable names with two underscores (i.e. __foo), and they effectively
> become private.[/color]
The double-leading-underscore stuff has nothing to do with "privacy".
It's meant to protect from *accidental* overriding of implementation stuff.
(snip)
[color=blue]
> Yes, that is is a risk. Most people deal with that risk by doing a lot of
> testing (which you should be doing anyway). If you really want to, you can
> use the __slots__ technique to prevent this particular bug from happening
> (although the purists will tell you that this is not what __slots__ was
> designed for).[/color]
Ok, so I must be a purist !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
|

April 11th, 2006, 07:35 PM
|
|
|
Re: About classes and OOP in Python
>I think it's important not to wrongly confuse 'OOP' with ''data hiding'[color=blue]
>or any other aspect you may be familiar with from Java or C++. The
>primary concept behind OOP is not buzzwords such as abstraction,
>encapsulation, polymorphism, etc etc, but the fact that your program
>consists of objects maintaining their own state, working together to
>produce the required results, as opposed to the procedural method where
>the program consists of functions that operate on a separate data set.[/color]
Isn't "inheritance" an important buzzword for OOP?
--
Regards,
Casey
|

April 11th, 2006, 08:25 PM
|
|
|
Re: About classes and OOP in Python
On 2006-04-11, Michele Simionato <michele.simionato@gmail.com> wrote:[color=blue]
> Roy Smith wrote:
><snip>[color=green]
>> That being said, you can indeed have private data in Python. Just prefix
>> your variable names with two underscores (i.e. __foo), and they effectively
>> become private. Yes, you can bypass this if you really want to, but then
>> again, you can bypass private in C++ too.[/color][/color]
[color=blue]
> Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
> on the contrary is a *protected* name ("touch me, touch me, don't worry
> I am protected against inheritance!").
> This is a common misconception, I made the error myself in the past.[/color]
Please explain! I didn't think _foo meant anything special, __foo
expands to _classname__foo for some sort of name-hiding. What am I
missing?
|

April 12th, 2006, 02:55 AM
|
|
|
Re: About classes and OOP in Python
On Tue, 11 Apr 2006 18:20:13 +0000, Casey Hawthorne wrote:
[color=blue][color=green]
>>I think it's important not to wrongly confuse 'OOP' with ''data hiding'
>>or any other aspect you may be familiar with from Java or C++. The
>>primary concept behind OOP is not buzzwords such as abstraction,
>>encapsulation, polymorphism, etc etc, but the fact that your program
>>consists of objects maintaining their own state, working together to
>>produce the required results, as opposed to the procedural method where
>>the program consists of functions that operate on a separate data set.[/color]
>
> Isn't "inheritance" an important buzzword for OOP?[/color]
Of course inheritance is an important and desirable feature of OOP, but it
isn't a necessary feature. Python built-in objects like int, list etc.
were still objects even before you could inherit from them.
I don't know of many other OO languages that didn't/don't have
inheritance, but there was at least one: Apple's Hypertalk, back in the
late 80s early 90s.
--
Steven.
|

April 12th, 2006, 03:15 AM
|
|
|
Re: About classes and OOP in Python
Michele Simionato wrote:[color=blue]
> Roy Smith wrote:
> <snip>[color=green]
> > That being said, you can indeed have private data in Python. Just prefix
> > your variable names with two underscores (i.e. __foo), and they effectively
> > become private. Yes, you can bypass this if you really want to, but then
> > again, you can bypass private in C++ too.[/color]
>
> Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
> on the contrary is a *protected* name ("touch me, touch me, don't worry
> I am protected against inheritance!").
> This is a common misconception, I made the error myself in the past.[/color]
Sure, if you only consider "private" and "protected" as they're defined
in a dictionary. But then you'd be ignoring the meanings of the
public/private/protected keywords in virtually every language that has
them. http://www.google.com/search?q=public+private+protected
Python doesn't have these keywords, but most Python programmers are at
least somewhat familiar with a language that does use them. For the
sake of clarity:
__foo ~= private = used internally by base class only
_foo ~= protected = used internally by base and derived classes
The Python docs use the above definitions.
--Ben
|

April 12th, 2006, 06:45 AM
|
|
|
Re: About classes and OOP in Python
Steven D'Aprano schrieb:
[color=blue]
> I don't know of many other OO languages that didn't/don't have
> inheritance,[/color]
VB4 - VB6
--
Mit freundlichen Grüßen,
Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung
http://www.gregor-horvath.com
|

April 12th, 2006, 09:55 AM
|
|
|
Re: About classes and OOP in Python
Ben C wrote:[color=blue]
> On 2006-04-11, Michele Simionato <michele.simionato@gmail.com> wrote:
>[color=green]
>>Roy Smith wrote:
>><snip>
>>[color=darkred]
>>>That being said, you can indeed have private data in Python. Just prefix
>>>your variable names with two underscores (i.e. __foo), and they effectively
>>>become private. Yes, you can bypass this if you really want to, but then
>>>again, you can bypass private in C++ too.[/color][/color]
>
>[color=green]
>>Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
>>on the contrary is a *protected* name ("touch me, touch me, don't worry
>>I am protected against inheritance!").
>>This is a common misconception, I made the error myself in the past.[/color]
>
>
> Please explain! I didn't think _foo meant anything special,[/color]
It doesn't mean anything special in the language itself - it's a
convention between programmers. Just like ALL_CAPS names is a convention
for (pseudo) symbolic constants. Python relies a lot on conventions.
[color=blue]
> __foo
> expands to _classname__foo for some sort of name-hiding.[/color]
s/hiding/mangling/
[color=blue]
> What am I
> missing?[/color]
the __name_mangling mechanism is meant to protect some attributes to be
*accidentaly* overridden. It's useful for classes meant to be subclassed
(ie in a framework). It has nothing to do with access restriction - you
still can access such an attribute.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
|

April 12th, 2006, 10:05 AM
|
|
|
Re: About classes and OOP in Python
Casey Hawthorne wrote:[color=blue][color=green]
>>I think it's important not to wrongly confuse 'OOP' with ''data hiding'
>>or any other aspect you may be familiar with from Java or C++. The
>>primary concept behind OOP is not buzzwords such as abstraction,
>>encapsulation, polymorphism, etc etc, but the fact that your program
>>consists of objects maintaining their own state, working together to
>>produce the required results, as opposed to the procedural method where
>>the program consists of functions that operate on a separate data set.[/color]
>
>
> Isn't "inheritance" an important buzzword for OOP?[/color]
Which kind of inheritance ? subtyping or implementation inheritance ?-)
FWIW, subtyping is implicit in dynamically typed languages, so they
don't need support for such a mechanism. And implementation inheritance
is not much more than a special case of composition/delegation, so it's
almost useless in a language that have a good support for delegation
(which we have in Python, thanks to __getattr__/__setattr__).
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
|

April 12th, 2006, 11:15 AM
|
|
|
Re: About classes and OOP in Python
Michele Simionato wrote:[color=blue]
> Roy Smith wrote:
> <snip>[color=green]
>> That being said, you can indeed have private data in Python. Just prefix
>> your variable names with two underscores (i.e. __foo), and they effectively
>> become private. Yes, you can bypass this if you really want to, but then
>> again, you can bypass private in C++ too.[/color]
>
> Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
> on the contrary is a *protected* name ("touch me, touch me, don't worry
> I am protected against inheritance!").
> This is a common misconception, I made the error myself in the past.[/color]
While your wording makes sense, it's probably confusing for anyone
with a C++ background, where private roughly means "only accessible
within the actual class" and protected roughly means "only accessible
within the class and other classes derived from it".
|

April 12th, 2006, 12:25 PM
|
|
|
Re: About classes and OOP in Python
Gregor Horvath wrote:[color=blue]
> Steven D'Aprano schrieb:
>
>[color=green]
>>I don't know of many other OO languages that didn't/don't have
>>inheritance,[/color]
>
>
> VB4 - VB6
>[/color]
VB6 has a kind of inheritance via interface/delegation. The interface
part is for subtyping, the delegation part (which has to be done
manually - yuck) is for implementation inheritance. Needless to say it's
a king-size PITA...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb@xiludom.gro'.split('@')])"
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|
|
What is Bytes?
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over network members.
|