12

What's wrong with this? From objective, and functional standpoints?

import sys
class EncapsulationClass(object):
 def __init__(self):
 self.privates = ["__dict__", "privates", "protected", "a"]
 self.protected = ["b"]
 print self.privates
 self.a = 1
 self.b = 2
 self.c = 3
 pass
 def __getattribute__(self, name):
 if sys._getframe(1).f_code.co_argcount == 0:
 if name in self.privates:
 raise Exception("Access to private attribute \"%s\" is not allowed" % name)
 else:
 return object.__getattribute__(self, name)
 else:
 return object.__getattribute__(self, name)
 def __setattr__(self, name, value):
 if sys._getframe(1).f_code.co_argcount == 0:
 if name in self.privates:
 raise Exception("Setting private attribute \"%s\" is not allowed" % name)
 elif name in self.protected:
 raise Exception("Setting protected attribute \"%s\" is not allowed" % name)
 else:
 return object.__setattr__(self, name, value)
 else:
 return object.__setattr__(self, name, value)
example = EncapsulationClass()
example.a = 10 # Exception: Setting private attribute "a" is not allowed
example.b = 10 # Exception: Setting protected attribute "b" is not allowed
example.c = 10 # example.c == 10
example.__dict__["privates"] # Exception: Setting protected attribute "b" is not allowed

What would actually be wrong with doing something like this?

Is there any better way to achieve encapsulation in Python?

kenorb
169k96 gold badges712 silver badges796 bronze badges
asked Oct 6, 2014 at 12:48
13
  • 4
    ...what do you mean? What do you think is wrong with it? Does it run? Commented Oct 6, 2014 at 12:53
  • 2
    Could've asked in codereview Commented Oct 6, 2014 at 12:56
  • It seems to work fine, yes, but i so often see people saying "python does not have encapsulation", so presumed it couldn't be as simple as this. Commented Oct 6, 2014 at 12:57
  • 2
    I wouldn't call code that accesses sys._getframe(1).f_code.co_argcount "simple", but never mind. What happens if I do EncapsulationClass.protected = [] from my code? Commented Oct 6, 2014 at 12:59
  • @DanielRoseman - you break it! I didn't spot that one... Commented Oct 6, 2014 at 13:01

3 Answers 3

48

Python has encapsulation - you are using it in your class.

What it doesn't have is access control such as private and protected attributes. However, in Python, there is an attribute naming convention to denote private attributes by prefixing the attribute with one or two underscores, e.g:

self._a
self.__a 

A single underscore indicates to the user of a class that an attribute should be considered private to the class, and should not be accessed directly.

A double underscore indicates the same, however, Python will mangle the attribute name somewhat to attempt to hide it.

class C(object):
 def __init__(self):
 self.a = 123 # OK to access directly
 self._a = 123 # should be considered private
 self.__a = 123 # considered private, name mangled
>>> c = C()
>>> c.a
123
>>> c._a
123
>>> c.__a
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__a'
>>> c._C__a
123

You can see in the last example that the name was changed from __a to _C__a, although it is still accessible within the class as self.__a.

answered Oct 6, 2014 at 13:08
Sign up to request clarification or add additional context in comments.

7 Comments

I know all this, this isn't quite the same as what i'm talking about though, and it seems that there are two definitions of encapsulation. One of them is just the packign of several pieces of data into a class, and the other is to do with actually hiding the data / making it inaccessible. the __a stuff i'm fine with, but that's not really the same as what i'm after - i'm interested more in emulating the private, protected, etc. variable modifiers seen in other languages.
My understanding of the whole __a variables was just that it's a method to let people using your codes know that they are not variables you intend to have used outside of the module - and as such people wouldn't rely on them, as they're liable to change at any time.
@Will - yes, encapsulation usually includes a mechanism for restricting access as you say. And yes, __ is a convention, as I said.
@PM2Ring i'm aware of this, and have read exactly that before. It's more of a curiosity thing than disagreeing with the design decisions of python
|
1

Well, Python does not have encapsulation as a sort of "philosophical" decision, in the same way that we use duck typing a lot. Personally I don't see the point of using private or protected arguments in a Python code.

Speaking of your code, it seems to work fine with the following getters and setters:

def set_a(self, v):
 self.a = v
def get_a(self):
 return self.a

if you make the following modification to your last line of __ getattribute __(self, name):

return object.__getattribute__(self, name)

However, you can use sort of a notion of variable-protecting, if you prefix your private variables with __, as mhawke mentioned. Plus, Daniel's comment points out a limitation of your list arguments. You could keep the protected "get/set" behaviour by adding "private" and "protected"in your private list.

answered Oct 6, 2014 at 13:10

Comments

0

In Mark Lutz's book Learning Python, Fifth edition, he mentioned a way of simulating encapsulation of class level like this:

"""
Created on Sun Oct 4 10:16:30 2020
@author: Mark Lutz
A typical implementation of encapsulation in python,
to use, call:@private(‘var1’, ‘var2’...)
"""
def private(*values):
 def decorator(cls):
 class Proxy:
 def __init__(self, *args, **kwargs):
 self.inst = cls(*args, **kwargs)
 def __call__(self, cls, *args, **kwargs):
 return self.inst
 def __getattr__(self, attr):
 if attr in values:
 raise AttributeError("Private valueiables are not accessible!")
 else: return getattr(self.inst, attr)
 def __setattr__(self, attr, val):
 # Allow access inside the class
 if attr == 'inst': self.__dict__[attr] = val
 elif attr in values:
 raise AttributeError("Private valueiables are not accessible!")
 else: setattr(self.inst, attr, val)
 def __str__(self):
 return self.inst.__str__()
 return Proxy
 return decorator

this can be used for class-level encapsulation (e.g.limiting the access of a variable or method in a class).

For module-level encapsulation, however, the only way that I can think of is that you create a file and write the init.py. However if those who writes the client program knows the structure of your file / package, this can still not stop them from importing stuff.

answered Jul 11, 2021 at 12:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.