Harry Hache Harry Hache - 2 years ago 141
Python Question

Python class returning value

I'm trying to create a class that returns a value, not self.

I will show you an example comparing with a list:

>>> l = list()
>>> print(l)
>>> class MyClass:
>>> pass

>>> mc = MyClass()
>>> print mc
<__main__.MyClass instance at 0x02892508>

I need that MyClass returns a list, like
does, not the instance info. I know that I can make a subclass of list. But is there a way to do it without subclassing?

I want to imitate a list (or other objects):

>>> l1 = list()
>>> l2 = list()
>>> l1
>>> l2
>>> l1 == l2
>>> class MyClass():
def __repr__(self):
return '[]'

>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1
>>> m2
>>> m1 == m2

Why is
m1 == m2
False? This is the question.

I'm sorry if I don't respond to all of you. I'm trying all the solutions you give me. I cant use
, because I need to use functions like setitem, getitem, etc.

Answer Source

I guess what you mean is a way to turn your class into kind of a list without subclassing list

I so, just make a method that returns a list.

def MyClass():
    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def get_list(self):
        return [self.value1, self.value2...]

>>>print MyClass().get_list()
[1, 2...]

If you meant that print MyClass() will print a list, just override __repr__:

class MyClass():        
    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def __repr__(self):
        return repr([self.value1, self.value2])

EDIT: I see you meant how to make objects compare. For that, you override the __cmp__ method.

class MyClass():
    def __cmp__(self, other):
        return cmp(self.get_list(), other.get_list())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download