[BangPypers] Object Oriented Programming in python

Noufal Ibrahim noufal at nibrahim.net.in
Mon Oct 21 07:42:27 CEST 2013

Saager Mhatre <saager.mhatre at gmail.com> writes:


> Sigh! Implementing a reasonably important feature in an obscure manner
> (that too, not completely, since even slots are accessible from
> outside an object) is not in keeping with friendliness. I say this
> feature is reasonably important since it is repeatedly brought up
> every few months with little to no satisfactory responses most of
> which is 'we are all adults here', which I am hard pressed to accept
> as a generalization on account of all the atrocious code mentioned
> above.

__slots__ are not meant for data hiding. They're meant as a final
"trick" to save memory when you have a large number of objects of the
class you're interested in.

If you define a __slots__ variable, you lose the class dictionary (since
that consumes some amount of memory) but you get smaller objects. The
gory details are here

but here's what it looks like.

>>> class Foo(object): 
...   __slots__ = ['bar']
...   def __init__(self):
...     self.bar = "Hello"
...   def display(self):
...     print self.bar
>>> x = Foo()
>>> dir(x) # Uses slots. No __dict__
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar', 'display']
>>> class Bar(object):
...   def __init__(self):
...     self.foo = "Hello"
...   def display(self):
...     print self.bar
>>> y = Bar()
>>> dir(y) # No slots so you have the __dict__
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'display', 'foo']
>>> import sys
>>> sys.getsizeof(x)
>>> sys.getsizeof(y)

As for the rest of your points, I agree with some. I'm generally
gravitating towards statically typed languages of late so my comments
will be vague anyway. 


More information about the BangPypers mailing list