1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

That is great. Thanks! I had been wondering what repr was for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.