473,796 Members | 2,476 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
19 1419
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.
The double-leading-underscore stuff has nothing to do with "privacy".
It's meant to protect from *accidental* overriding of implementation stuff.

(snip)
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).


Ok, so I must be a purist !-)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Apr 11 '06 #11
>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,
encapsulatio n, 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.


Isn't "inheritanc e" an important buzzword for OOP?
--
Regards,
Casey
Apr 11 '06 #12
On 2006-04-11, Michele Simionato <mi************ ***@gmail.com> wrote:
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.


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?
Apr 11 '06 #13
On Tue, 11 Apr 2006 18:20:13 +0000, Casey Hawthorne 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.


Isn't "inheritanc e" an important buzzword for OOP?


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.

Apr 12 '06 #14
Michele Simionato wrote:
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.


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

Apr 12 '06 #15
Steven D'Aprano schrieb:
I don't know of many other OO languages that didn't/don't have
inheritance,


VB4 - VB6

--
Mit freundlichen Grüßen,
Ing. Gregor Horvath, Industrieberatu ng & Softwareentwick lung
http://www.gregor-horvath.com
Apr 12 '06 #16
Ben C wrote:
On 2006-04-11, Michele Simionato <mi************ ***@gmail.com> wrote:
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.

Please explain! I didn't think _foo meant anything special,


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.
__foo
expands to _classname__foo for some sort of name-hiding.
s/hiding/mangling/
What am I
missing?


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 'o****@xiludom. gro'.split('@')])"
Apr 12 '06 #17
Casey Hawthorne 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.

Isn't "inheritanc e" an important buzzword for OOP?


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 'o****@xiludom. gro'.split('@')])"
Apr 12 '06 #18
Michele Simionato wrote:
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.


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".
Apr 12 '06 #19
Gregor Horvath wrote:
Steven D'Aprano schrieb:

I don't know of many other OO languages that didn't/don't have
inheritance ,

VB4 - VB6

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

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

Similar topics

220
19175
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
6580
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
3182
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
1660
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
3309
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
4414
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
7891
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
1753
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
9529
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,...
1
10176
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,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9054
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7550
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
6792
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
5443
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
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4119
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

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.