Skip to content Skip to sidebar Skip to footer

Change What Is Returned On Screen By Class Instance

Lets say I have a class Hello, and I do the following: >> a = Hello() >> a This will return the following: <__main__.Hello instance at 0x123abc> How do I change

Solution 1:

add:

classHello(object):def__str__(self):
        return"HI"def__repr__(self):
        return"Hi"


>>> a = Hello()
>>> a           --> calls __repr__ method
Hi        
>>> print a     --> calls __str__ method
HI 

Solution 2:

In the interest of answering the EXACT question being asked, what you're asking about, "change what's returned by calling a class", is roughly the semantics of a metaclass.

So, for the sake of argument, lets suppose we want to have a class that looks like this:

classFoo(object):
    __metaclass__ = MyMeta
    def__init__(self, bar):
        print"Hello from", self
        self.bar

actually satisfy:

>>> myBar = object()
>>> myFoo = Foo(myBar)
Hello from <__main__Foo object at 0x...>
>>> myFoo is myBar
True

Specifically, we have a real class, which really gets instantiated when called upon, but the return value is something else, we can do that, so long as MyMeta looks about like so:

classMyMeta(type):
    def__call__(cls, *args, **kwargs):
        self = super(MyMeta, cls).__call__(*args, **kwargs)
        return self.bar

Of course, I would not do this.

Post a Comment for "Change What Is Returned On Screen By Class Instance"