Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulating a list in Python

Tags:

python

types

list

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?

like image 572
la11111 Avatar asked Sep 30 '12 22:09

la11111


2 Answers

The method you are looking for wolud be __repr__. See also http://docs.python.org/reference/datamodel.html#object.repr

like image 162
jfrohnhofen Avatar answered Oct 04 '22 19:10

jfrohnhofen


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:

class MyList(object):
    def __repr__(self):
        # iterate over elements and add each one to resulting string

As pointed in the comments, str() calls __repr__ if __str__ isn't defined, but repr() doesn't call __str__ if __repr__ isn't defined.

like image 27
Óscar López Avatar answered Oct 04 '22 21:10

Óscar López