In an attempt to discover the boundaries of Python as a language I'm exploring whether it is possible to go further with information hiding than the convention of using a leading underscore to denote 'private' implementation details.
I have managed to achieve some additional level of privacy of fields and methods using code such as this to copy 'public' stuff from a locally defined class:
from __future__ import print_function
class Dog(object):
def __init__(self):
class Guts(object):
def __init__(self):
self._dog_sound = "woof"
self._repeat = 1
def _make_sound(self):
for _ in range(self._repeat):
print(self._dog_sound)
def get_repeat(self):
return self._repeat
def set_repeat(self, value):
self._repeat = value
@property
def repeat(self):
return self._repeat
@repeat.setter
def repeat(self, value):
self._repeat = value
def speak(self):
self._make_sound()
guts = Guts()
# Make public methods
self.speak = guts.speak
self.set_repeat = guts.set_repeat
self.get_repeat = guts.get_repeat
dog = Dog()
print("Speak once:")
dog.speak()
print("Speak twice:")
dog.set_repeat(2)
dog.speak()
However, I'm struggling to find a way to do the same for the property setter and getter.
I want to be able to write code like this:
print("Speak thrice:")
dog.repeat = 3
dog.speak()
and for it to actually print 'woof' three times.
I've tried all of the following in Dog.__init__
, none of which blow up, but neither do they seem to have any effect:
Dog.repeat = guts.repeat
self.repeat = guts.repeat
Dog.repeat = Guts.repeat
self.repeat = Guts.repeat
self.repeat = property(Guts.repeat.getter, Guts.repeat.setter)
self.repeat = property(Guts.repeat.fget, Guts.repeat.fset)