Mathieson
Mathieson

Reputation: 1282

Mimicking functionality of built-in types

I am curious if there is a way to mimic the same kind of functionality as built-in types with custom classes. The best way to explain what I am looking for is with an example.

class MyClass(object):

    def __init__(self, val):
        self._returnVal = val

myObject = MyClass('test')
print myObject

Rather than the above code returning:

<__main__.MyClass object at 0x023861F0>

Is there a way to get it so when we call on the object it automatically returns self._returnVal, but also still allows us to call the methods that exist on myObject?

Upvotes: 1

Views: 99

Answers (1)

srgerg
srgerg

Reputation: 19329

You could override the __repr__ method:

class MyClass(object):
    def __init__(self, val):
        self._returnVal = val
    def __repr__(self):
        return self._returnVal

Now if I instantiate the class I get:

>>> myObject = MyClass('test')
>>> print myObject
test

Upvotes: 2

Related Questions