_repr_() 函数的作用

class Node:
    def __init__(self, value):
        self._value_plus = value + 10
        self._value_current = value
        self._children = []

    def __repr__(self):
        return 'ooo{!r}'.format(self._value_plus)

    def add_child(self, node):
        display('transfored_node_dict:{}'.format(node.__dict__))
        display('transfored_node:{}'.format(node))
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

# Example
if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    print(child1.__dict__)
    print(root.__dict__)

程序输出:
“transfored_node_dict:{’_value_plus’: 11, ‘_value_current’: 1, ‘_children’: []}”
‘transfored_node:ooo11’
{’_value_plus’: 11, ‘_value_current’: 1, ‘_children’: []}
{’_value_plus’: 10, ‘_value_current’: 0, 'children’: [ooo11]}
通过修改_repr
() 函数的return的值,可以更改add_child函数中node的输出格式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值