0
Q:

python __repr__

>>>x=4
>>>repr(x)
'4'
>>>str(x)
'4'
>>>y='stringy'
>>>repr(y)
"'stringy'"
>>>str(y)
'stringy'
1
very briefly
 - The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)
 - __repr__ goal is to be unambiguous
 - __str__ goal is to be readable
 - Container’s __str__ uses contained objects’ __repr__
 
see source for more info
1

class Person:
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    def __repr__(self):
        return {'name':self.name, 'age':self.age}

    def __str__(self):
        return 'Person(name='+self.name+', age='+str(self.age)+ ')'
0
>>>repr(y)
"'a string'"
>>>y2=eval(repr(y))
>>>y==y2
True
0
class Car:
    def __init__(self, color, mileage):
        self.color = color
        self.mileage = mileage

    def __str__(self):
        return 'a {self.color} car'.format(self=self)
0

New to Communities?

Join the community