Reputation: 227
class A:
def __init__(self, message):
self.message = message
def __repr__(self):
return self.message
print A("Hello")
The above code prints prints "Hello", as a string is returned. But I want to return a list by default. Like if I write :
class A:
def __init__(self, message):
self.message = message
def __repr__(self):
mylist = [self.message]
return mylist
print A("Hello")
The above code gives an error TypeError: __str__ returned non-string (type list)
I cannot create an object of the class, as i need to handle this as an exception. like:
try:
#some code which passes parameters to constructor of A if this fails.
except A as e:
#here I want e as a list instead of string.
Is there any way to return a list ?
Upvotes: 1
Views: 5769
Reputation: 6521
Here's an idea just for fun. I am using the call for returning a non-string output. In the example below, a tuple.
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
new_x = self.x + other.x
new_y = self.y + other.y
return MyClass(new_x, new_y)
def __repr__(self):
return "({},{})".format(self.x, self.y)
def __call__(self):
return (self.x, self.y)
Output:
>>> m1 = MyClass(10, 20)
>>> m1
(10,20)
>>> m1()
(10, 20)
>>> type(m1())
<type 'tuple'>
Upvotes: 2
Reputation: 1028
__str__
and __repr__
methods must return strings. You have to make a custom getter function.
For instance:
class A:
def __init__(self, message):
self.message = message
def get_message_as_list(self):
return [self.message]
my_object = A("Hello")
print(my_object.get_message_as_list())
As jonrsharpe said, you can't really use a magic (double underscored) method for this.
Upvotes: 4
Reputation: 2243
This is a bad idea. __repr__
should always return a str because it gets used by lots of internals (like you see here in print
). For info read on: https://docs.python.org/3/reference/datamodel.html#object.repr
Upvotes: 3