I’m working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
>>> a = [1,2,3] >>> a [1,2,3]
what I’m getting, essentially:
>>> a = MyList([1,2,3]) >>> a <MyList object at 0xdeadbeef>
I can’t figure out which dunder method (if any) would allow me to customize this behavior?
I’d think it would be __ get __ ? although list() doesn’t implement get/set/delete – i guess because it’s a built-in?
You should override the
__repr__method in you class (and optionally the__str__method too), see this post for a discussion on the differences.Something like this:
As pointed in the comments,
str()calls__repr__if__str__isn’t defined, butrepr()doesn’t call__str__if__repr__isn’t defined.