內置方法__repr__

class School():
    def __init__(self, name, address):
        self.name = name
        self.address = address


xh = School('alex', 'aa')
print(xh)

輸出結果:

<__main__.School object at 0x00000000006C7CC0>

如果添加__repr__這個方法:就會有下面的結果

class School():

    def __repr__(self):   # 內置的方法 讓 打印的對象 豐富起來
        show_str = ''
        for key in self.__dict__:
            show_str += '%s:%s\n' % (key, self.__dict__[key])
        return show_str

    def __init__(self, name, address):
        self.name = name
        self.address = address


xh = School('alex', 'aa')
print(xh)

輸出結果:

name:alex
address:aa

最新裝逼版

使用表格形式打印

from prettytable import PrettyTable

class Foo:
    def __repr__(self):
        table_head_name = []
        table_value = []
        for key in self.__dict__:
            table_head_name.append(key)
            table_value.append(self.__dict__[key])
        table_show = PrettyTable(table_head_name)
        table_show.add_row(table_value)
        return str(table_show)


class School(Foo):

    def __init__(self, name, address):
        self.name = name
        self.address = address


xh = School('alex', 'aa')
print(xh)

輸出結果:

+---------+------+
| address | name |
+---------+------+
|    aa   | alex |
+---------+------+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章