references/pointers in Python?
Gordon McMillan
gmcm at hypernet.com
Thu Sep 13 19:14:46 EDT 2001
Patrick K. O'Brien wrote:
> Do you have a good way of creating a Facade class that wraps immutable
> attributes with the same simple dot syntax as the original class? Below
> is a very simple example that *doesn't* work, that would appear to
> benefit if we could create references. Class A is a class with many
> simple true/false attributes. Class B is a Facade that simplifies the
> interface to A by only exposing a few of its attributes. When the
> attributes are methods, or mutable types, the following style of code
> works. But it fails in the example below which has only immutable int
> types:
...
>>>> class A:
> ... def __init__(self):
> ... self.toggle01 = 0
> ... self.toggle02 = 0
> ... self.toggle03 = 0
> ... self.toggle04 = 0
> ... self.toggle05 = 0
> ... self.toggle97 = 0
> ... self.toggle98 = 0
> ... self.toggle99 = 0
> ...
>>>> class B:
> ... def __init__(self, other):
> ... self.toggle01 = other.toggle01
> ... self.toggle02 = other.toggle02
> ... self.toggle03 = other.toggle03
...
> I would love to see a solution where something like this would work, as
> I have a need for exactly this kind of Facade class. Note that I do not
> want to have to create get() and set() methods. I'd like access to
> immutable types to transparently pass through class B. Any suggestions?
Lots of ways you could do this. Probably the most "pythonic" (at least,
before Python 2.2) would be:
class B:
_attrs = ('toggle01', 'toggle02', 'toggle03')
def __init__(self, other):
self.__dict__['other'] = other
def __getattr__(self, nm):
if nm in self._attrs:
return getattr(self.other, nm)
raise AttributeError, nm
def __setattr__(self, nm, val):
if nm in self._attrs:
return setattr(self.other, nm, val)
raise AttributeError, nm
This is a typical kind of pattern where class A is out of your control.
Where class A *is* under your control, I think you'll find a better
way to do it (once you've unlearned all the tricks you need to survive
in other object models).
- Gordon
More information about the Python-list
mailing list