So i want to something like this in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return self.name, self.age
p = Person('A', 20)
Then hope to call object p directly to get the tuple (self.name, self.age)
But as you can see when you run this program, you get the problem:
TypeError: __repr__ returned non-string (type tuple)
How can have this behavior?
Thanks!
Note: The problem is not specific to the tuple data type; it can be anything, like a pandas dataframe for example. I just want to return some attribute data, whatever type it is.
As the error suggest, your __repr__
must return a string
def __repr__(self):
return self.name + str(self.age)
Now, if your goal is to write a custom way of representing your object as a tuple, what you are looking for is _iter__
instead,
def __iter__(self):
yield self.name
yield self.age
p = Person('A', 20)
print(tuple(p))
>>>>('A', 20)
You can make Person
iterable:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __iter__(self):
yield self.name
yield self.age
name, age = p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With