Simple Question: simulation of primitive data types

Alex Martelli aleaxit at yahoo.com
Sat Apr 21 13:33:16 EDT 2001


"Thomas Weholt" <thomas at cintra.no> wrote in message
news:XaiE6.1108$cg4.16580 at news1.oke.nextra.no...
> I got a class like this:
>
> class myclass:
>     def __init__(self, val):
>         self.val = val
>
> # create an instance
> x = myclass(1)
>
> I want the statement 'print x' to result in the printing of '1' on the
> screen, not using __str__ or __repr__, but returning the actual value of
> self.val each time the instance is called.

If it was about *calling*, as you say in this last line, you could
easily do it by adding a __call__ method to myclass.  But calling
is only effected with parentheses after the callable (or indirectly
with apply, etc), as in
    print x()
as opposed to
    print x
so it doesn't meed the request at the start of the paragraph.

If you're saying you want the number 1 to be used every time
reference x is used in any context, I don't think you can do it
in Python.

> I cannot remember how to implement this. Any hints?

Hint: since there is nothing special about argument passing,
and 'type', 'isinstance', etc, are all normal functions from this
point of view, if it was possible to do what you ask (at the
start of the previous paragraph quoted), then type(x) would
be integer-type, isinstance(x, myclass) would have to be 0
just like isinstance(1, myclass), dir(x) would always be [],
getattr(x,'val') would have to raise an AttributeError just
like getattr(1, 'val') would, and so on, and so forth.  And the
semantics of, for example, x.val, are always identical to
those of getattr(x,'val'), so that should similarly fail too.

In other words, x would have to behave in all ways exactly
like number 1.  Oh, yeah, I was almost forgetting -- id(x)
would also have to be 1, so 'x is 1' would be true.  In NO
way could the object referenced by x behave differently from
1, since it WOULD be the object 1, it seems to me.


Alex







More information about the Python-list mailing list