如果想对比两个节点 (的各种值) ,就用 _eq_ 来重载 == 运算符,用 _lt_ 来重载 < 运算符,用 _ge_ 来重载 >= 。
- 1class Node:
- 2 """ A struct to denote the node of a binary tree.
- 3 It contains a value and pointers to left and right children.
- 4 """
- 5 def __init__(self, value, left=None, right=None):
- 6 self.value = value
- 7 self.left = left
- 8 self.right = right
- 9
- 10 def __eq__(self, other):
- 11 return self.value == other.value
- 12
- 13 def __lt__(self, other):
- 14 return self.value < other.value
- 15
- 16 def __ge__(self, other):
- 17 return self.value >= other.value
- 18
- 19
- 20left = Node(4)
- 21root = Node(5, left)
- 22print(left == root) # False
- 23print(left < root) # True
- 24print(left >= root) # False
想要了解更多魔术方法,请前往:
https://www.tutorialsteacher.com/python/magic-methods-in-python
或者使用官方文档,只是有一点点难读:
https://docs.python.org/3/reference/datamodel.html#special-method-names
这里,还要重点安利几种魔术方法:
一是 _len_ :重载 len() 函数用的。
二是 _str_:重载 str() 函数用的。
三是 _iter_:想让object变成迭代器,就用这个。有了它,还可以在object上调用 next() 函数。
对于像节点这样的类,我们已经知道了它支持的所有属性 (Attributes) :value、left和right,那就可以用 _slots_ 来表示这些值。这样有助于提升性能,节省内存。
- 1class Node:
- 2 """ A struct to denote the node of a binary tree.
- 3 It contains a value and pointers to left and right children.
- 4 """
- 5 __slots__ = ('value', 'left', 'right')
- 6 def __init__(self, value, left=None, right=None):
- 7 self.value = value
- 8 self.left = left
- 9 self.right = right
想要全面了解 _slots_ 的优点和缺点,可以看看Aaron Hall的精彩回答:
https://stackoverflow.com/a/28059785/5029595
4、局部命名空间,对象的属性
locals() 函数,返回的是一个字典 (Dictionary) ,它包含了局部命名空间 (Local Namespace) 里定义的变量。l
- 1class Model1:
- 2 def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):
- 3 print(locals())
- 4 self.hidden_size = hidden_size
- 5 self.num_layers = num_layers
- 6 self.learning_rate = learning_rate
- 7
- 8model1 = Model1()
- 9
- 10==> {'learning_rate': 0.0003, 'num_layers': 3, 'hidden_size': 100, 'self': <__main__.Model1 object at 0x1069b1470>}
(编辑:ASP站长网)
|