3

У меня есть класс:

class MyClass():
    def __init__(self, n):
        self.n = n
    
    def __str__(self):
        return str(self.n)

и список arr, в котором лежат экземпляры класса:

arr = [MyClass(0), MyClass(1)]

как сделать так чтобы при print(arr) выводилось:

['0', '1']

а не:

[<__main__.MyClass object at 0xebeb3dc0>, <__main__.MyClass object at 0xebdcb580>]

полный код:

class MyClass():
    def __init__(self, n):
        self.n = n
    
    def __str__(self):
        return str(self.n)

arr = [MyClass(0), MyClass(1)]

print(arr)
0

1 ответ 1

9

Добавьте реализацию специального метода __repr__:

def __repr__(self):
    return str(self.n)
1
  • 2
    Тогда уж return repr(self.n) 21 окт 2020 в 13:47

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.