Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python object return attribute data when called directly

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.

like image 990
moctarjallo Avatar asked Aug 03 '18 12:08

moctarjallo


2 Answers

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)
like image 184
scharette Avatar answered Oct 11 '22 13:10

scharette


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
like image 39
chepner Avatar answered Oct 11 '22 13:10

chepner