Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104518

Encapsulation in Python

From Ben Mezger <me@benmezger.nl>
Newsgroups comp.lang.python
Subject Encapsulation in Python
Date 2016-03-10 10:41 -0300
Message-ID <mailman.132.1457617425.15725.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

Hi all,

I've been studying Object Oriented Theory using Java. Theoretically, all
attributes should be private, meaning no one except the methods itself
can access the attribute;

public class Foo {
    private int bar;
    ...

Normally in Java, we would write getters and setters to set/get the
attribute bar. However, in Python, we normally create a class like so;

class Foo(object):
    bar = 0
    ...

And we usually don't write any getters/setters (though they exist in
Python, I have not seen much projects making use of it).

We can easily encapsulate (data hiding) Foo's class using the '_'
(underscore) when creating a new attribute, however, this would require
all attributes to have a underscore.
According to this answer [1], it's acceptable to to expose your
attribute directly (Foo.bar = 0), so I wonder where the encapsulation
happens in Python? If I can access the attribute whenever I want (with
the except of using a underscore), what's the best way to encapsulate a
class in Python? Why aren't most of the projects not using
getters/setters and instead they access the variable directly?

Regards,

Ben Mezger

[1] - http://stackoverflow.com/q/4555932

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Encapsulation in Python Ben Mezger <me@benmezger.nl> - 2016-03-10 10:41 -0300
  Re: Encapsulation in Python Steven D'Aprano <steve@pearwood.info> - 2016-03-11 20:28 +1100
    Re: Encapsulation in Python Rick Johnson <rantingrickjohnson@gmail.com> - 2016-03-11 16:45 -0800
      Re: Encapsulation in Python dieter <dieter@handshake.de> - 2016-03-12 10:42 +0100
        Re: Encapsulation in Python Rick Johnson <rantingrickjohnson@gmail.com> - 2016-03-12 07:03 -0800
      Re: Encapsulation in Python Chris Angelico <rosuav@gmail.com> - 2016-03-13 00:42 +1100

csiph-web