473,785 Members | 2,325 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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!

Apr 10 '06 #1
19 1418
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(sel f):
return 0;

prop = property(fget = getProperty)

t = Test()

print t.prop

t.prop = 100 # this will fail

Apr 10 '06 #2
"fyhuang" <fy*****@gmail. com> wrote:
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.
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.
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.
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).
My main question is that of why Python chooses to use this type of OOP
model and if it is planned to change.


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.
Apr 10 '06 #3
Em Seg, 2006-04-10 Ã*s 07:19 -0700, fyhuang escreveu:
class PythonClass:
private foo = "bar"
private var = 42
allow_readwrite ( [ foo, var ] )
You are aware that foo and var would become class-variables, not
instance-variables, right?

But you can always do:

class PythonClass(obj ect):
def __init__(self):
self.__foo = "bar"

foo = property(lambda self: self.__foo)
And then:
a = PythonClass()
a.foo 'bar' a.foo = 'baz' Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute
But you can also bypass this "security":
a._PythonClass_ _foo = 'baz'
a.foo

'baz'
But this was not a mistake, nobody mistakenly writes "_PythonClass__ ".
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


There's a PEP somewhere that proposes things like (same example I gave
earlier):

class PythonClass(obj ect):
def __init__(self):
self.__foo = "bar"

create property foo:
def get(self):
return self.__foo

--
Felipe.

Apr 10 '06 #4
fyhuang <fy*****@gmail. com> wrote:
[ ... ] 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.
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.
I'm wondering what the philosophy behind this is,
"We are all consenting adults." And probably experience of data
encapsulation being more of a hinderence than a benefit.
and if this
behaviour is going to change in any future release of Python.


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_n ames = set(allowed_nam es)
def __setattr__(sel f, name, value):
if not name.startswith ('_') and name not in self._allowed_n ames:
getattr(self, name)
self.__dict__[name] = value

(Someone else can do the new style class and the metaclass versions.)

--
\S -- si***@chiark.gr eenend.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
Apr 10 '06 #5
Hi,

fyhuang schrieb:
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


the answer is here:

http://tinyurl.com/obgho

--
Mit freundlichen Grüßen,
Ing. Gregor Horvath, Industrieberatu ng & Softwareentwick lung
http://www.gregor-horvath.com
Apr 10 '06 #6
fyhuang wrote:
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.


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

Apr 11 '06 #7
Ben Sizer wrote:
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.


+1 QOTW

</F>

Apr 11 '06 #8
Roy Smith wrote:
<snip>
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.


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

Apr 11 '06 #9
fyhuang wrote:
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.
Seems you're confusing encapsulation with data hiding.
Any
part of the code is allowed access to any variable in any class,
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.
and
even non-existant variables can be accessed:
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.
they are simply created.
I'm wondering what the philosophy behind this is,
Dynamism.
and if this
behaviour is going to change in any future release of Python.
Certainly not.
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.
Don't assume, verify. My own experience is that it's *much more* easy to
do OOP with a dynamic language.
For example, if the programmer typos a variable name
in an assignment, the assignment will probably not do what the
programmer intended.
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.
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 ] )
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.
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
What you want is named "property".
Anyways, these are just some speculatory suggestions.
Don't waste time with speculations. Read the Fine Manual instead, and
actually *use* Python.
My main question
is that of why Python chooses to use this type of OOP model and if it
is planned to change.


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 'o****@xiludom. gro'.split('@')])"
Apr 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

220
19164
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
54
6577
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature here, that feature there. Variations on style are of no interest to me. I'm coming at this from a...
39
3179
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am sure there are many discussions on the "problems" mentioned here. But I had this thoughts without looking into any forums or anything... it is kind of feedback.
5
1657
by: b-blochl | last post by:
I wonder about the huge traffic in the question how many tuples are dispensible. I find that a question of only ternary or quarterny order - use it or use it not (free after Shakespears "to be or not to be). Well, I had my part on that. But introducing students to python as a first programming language lists and tuples are astoninglishy always constant points of confusion as well as the other points of the citatet list. I will not...
28
3306
by: David MacQuigg | last post by:
I'm concerned that with all the focus on obj$func binding, &closures, and other not-so-pretty details of Prothon, that we are missing what is really good - the simplification of classes. There are a number of aspects to this simplification, but for me the unification of methods and functions is the biggest benefit. All methods look like functions (which students already understand). Prototypes (classes) look like modules. This will...
3
1420
by: arserlom | last post by:
Hello I have a question about inheritance in Python. I'd like to do something like this: class cl1: def __init__(self): self.a = 1 class cl2(cl1): def __init__(self): self.b = 2
97
4410
by: Cameron Laird | last post by:
QOTW: "Python makes it easy to implement algorithms." - casevh "Most of the discussion of immutables here seems to be caused by newcomers wanting to copy an idiom from another language which doesn't have immutable variables. Their real problem is usually with binding, not immutability." - Mike Meyer Among the treasures available in The Wiki is the current copy of "the Sorting min-howto":
161
7882
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.. (After reading that
3
2169
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder for a member variable of a Python object. It has to be given a value when defined, or set within a method. But what is the difference between an Attribute of a Class, a Descriptor in a Class, and a Property in a Class?
19
1752
by: adriancico | last post by:
Hi I am working on a python app, an outliner(a window with a TreeCtrl on the left to select a document, and a RichTextBox at the right to edit the current doc). I am familiarized with OOP concepts and terms but I lack practical experience
0
9481
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10095
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.