Simulating call of instance like a list or tuple
Michael Robin
me at mikerobin.com
Mon Jan 14 13:11:13 EST 2002
Brett wrote:
>It seems everyone is thinking that I want __repr__ or __str__, which
is in
>the right vein, but not quite it. I want the same functionality,
but I
>want to be able to return something other than a string
It's hard to say from his example, but it seems like he
knows what repr/str do, but he wants to *return* something else,
not just alter its printable representation.
I think maybe he wondering if there's a special method like __value__:
class Foo:
def __init__(self, obj):
self.obj = [obj]
def __value__(self): # warning: not Python
# Be careful not to return a new list here each time
# unless you really mean it and don't want to get mutated
return self.obj
>>>f = Foo(42)
>>>f.append('hi')
>>>f
[42, hi]
or something like that, where an instance can return something
other than "self" when it is referenced. (This is like ST's become:,
but done per-reference.)
Other examples:
class MyCachedObject:
def __init__(self, obj=None):
self._obj = obj
def __value__(self): # warning: not Python
if not self._obj:
self.swapIn()
return self._obj
def swapOut(self):
self._dbref = db.save(self._obj)
self._obj = None
def swapIn(self):
self._obj = db.load(self._dbref)
(In this universe __value__ is not called when another object
references
this one, it's done lazily when the object is de-referenced in any
way.)
Of course, __getattr__/__call__ are the prescribed ways of
achieving similar results, in a more fine-grained way.
This is *not* a feature request, just some thoughts - disasterous
ramifications not contemplated. (Well, many come to mind, but they're
not enumerated here anyway...)
Anyway, Brett, maybe you want to look at __getattr__ and __call__
if __repr__ is what you were looking for??
mike
"Jason Orendorff" <jason at jorendorff.com> wrote in message news:<mailman.1010944879.21874.python-list at python.org>...
> > It seems everyone is thinking that I want __repr__ or __str__, which is in
> > the right vein, but not quite it. I want the same functionality, but I
> > want to be able to return something other than a string. I don't think it
> > exists outside of the built-in classes.
>
> All the built-in types use __repr__ to do this, and they
> all return strings.
>
> Your __repr__ method should figure out the value you want to print,
> then convert it to a string.
>
> class MyClass:
> def __repr__(self):
> # Here's the data I want to display...
> data = self.my_data
> # Now convert it to a string and return that.
> return repr(data)
>
> >>> x = MyClass()
> >>> x.my_data = (3, 4, 'Poughkeepsie', 2.71828, u'\N{DAGGER}\N{BULLET}')
> >>> x
> (3, 4, 'Poughkeepsie', 2.71828, u'\u2020\u2022')
>
> ## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list