Python class returning value
If what you want is a way to turn your class into kind of a list without subclassing list , then 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())
Use __new__ to return value from a class.
As others suggest __repr__ , __str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.
Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585
class MyClass(): def __new__(cls): return list() #or anything you want >>> MyClass() [] #Returns a true list not a repr or string
class MyClass(): def __init__(self, a, b): self.value1 = a self.value2 = b def __call__(self): return [self.value1, self.value2]
>>> x = MyClass('foo','bar') >>> x() ['foo', 'bar']
I think you are very confused about what is occurring.
In Python, everything is an object:
- [] (a list) is an object
- ‘abcde’ (a string) is an object
- 1 (an integer) is an object
- MyClass() (an instance) is an object
- MyClass (a class) is also an object
- list (a type—much like a class) is also an object
They are all «values» in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.
When you call a class object (like MyClass() or list() ), it returns an instance of that class. ( list is really a type and not a class, but I am simplifying a bit here.)
When you print an object (i.e. get a string representation of an object), that object’s __str__ or __repr__ magic method is called and the returned value printed.
>>> class MyClass(object): . def __str__(self): . return "MyClass([])" . def __repr__(self): . return "I am an instance of MyClass at address "+hex(id(self)) . >>> m = MyClass() >>> print m MyClass([]) >>> m I am an instance of MyClass at address 0x108ed5a10 >>>
So what you are asking for, «I need that MyClass return a list, like list(), not the instance info,» does not make any sense. list() returns a list instance. MyClass() returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print them or look at them in the console, then create a __str__ and __repr__ method which represents them as you want them to be represented.
Update for new question about equality
Once again, __str__ and __repr__ are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__ value does not mean they are equal!
MyClass() != MyClass() because your class does not define how these would be equal, so it falls back to the default behavior (of the object type), which is that objects are only equal to themselves:
>>> m = MyClass() >>> m1 = m >>> m2 = m >>> m1 == m2 True >>> m3 = MyClass() >>> m1 == m3 False
If you want to change this, use one of the comparison magic methods
For example, you can have an object that is equal to everything:
>>> class MyClass(object): . def __eq__(self, other): . return True . >>> m1 = MyClass() >>> m2 = MyClass() >>> m1 == m2 True >>> m1 == m1 True >>> m1 == 1 True >>> m1 == None True >>> m1 == [] True
I think you should do two things:
- Take a look at this guide to magic method use in Python.
- Justify why you are not subclassing list if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:
class MyClass(object): def __init__(self): self._list = [] def __getattr__(self, name): return getattr(self._list, name) # __repr__ and __str__ methods are automatically created # for every class, so if we want to delegate these we must # do so explicitly def __repr__(self): return "MyClass(%s)" % repr(self._list) def __str__(self): return "MyClass(%s)" % str(self._list)
>>> c = MyClass() >>> c.append(1) >>> c MyClass([1])
Python class return value
Last updated: Feb 22, 2023
Reading time · 2 min
# Purpose of ‘return self’ from a class method in Python
The purposes of the return self statement from a class method are:
- The ability to chain multiple calls to a method because return self returns the instance object.
- Using the iterator protocol, which requires us to return self from the __iter__() method.
Copied!class Calc(): def __init__(self, number=0): self.number = number def add(self, value): self.number = self.number + value return self def subtract(self, value): self.number = self.number - value return self calc = Calc() calc.add(5).subtract(2).add(5) print(calc.number) # 👉️ 8 calc.subtract(5).add(3) print(calc.number) # 👉️ 6
The add and subtract methods in the Calc() class use a return self statement.
When we call an instance method, Python automatically passes self as the first argument to the method.
self represents an instance of the class — the instance on which the method was called.
When we return self from a class method, we basically return the instance object.
This allows us to chain multiple calls to the method in a single statement.
# Chaining multiple calls to a method that returns self
The add() and subtract() methods return the instance, so we can chain many calls to the methods in a single line, without storing the results in intermediary variables.
Copied!class Calc(): def __init__(self, number=0): self.number = number def add(self, value): self.number = self.number + value return self def subtract(self, value): self.number = self.number - value return self calc = Calc() calc.add(5).subtract(2).add(5) print(calc.number) # 👉️ 8
You aren’t going to see the pattern of method chaining often, but some libraries make use of it.
The idea is that each method returns an object, which allows the calls to be chained together in a single statement without storing the results in intermediary variables.
When you see syntax such as obj.a().a().b() , the code under the hood uses the method chaining pattern.
However, returning self from class methods is much more common when implementing the iterator protocol.
The _ _ iter _ _ () method must return the iterator object itself.
Here is an example of how to make a class iterable by implementing the __iter__() method.
Copied!class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): # 👇️ return `self` here return self def __next__(self): self.current += 1 if self.current self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3
The __iter__() method is implicitly called at the start of loops and returns the iterator object ( self ).
The __next__() method is implicitly called at each loop increment and returns the next value.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.