# Python乾貨整理之__str__
__str__是Python中類對象自帶的一個函數(通過其名字也能看出來,和__self__類似),那麼它有什麼作用呢?首先敲出下面的代碼運行一下看看結果是什麼:
class Person(object):
def __init__(self, name = 'tom', age = 10):
self.name = name
self.age = age
self.parent = None
tom = Person()
print(tom)
# 唔,在我這裏輸出了個看起來像是地址的東西
# >>> <__main__.Person object at 0x00000244B4A2EA90>
所以當我們打印一個實例化對象時,打印的其實是這個對象的地址。而通過自定義__str__()函數就可以幫助我們打印對象中相關的內容。
class Person(object):
def __init__(self, name = 'tom', age = 10):
self.name = name
self.age = age
self.parent = None
def __str__(self):
return "Your name is: " + self.name
tom = Person()
print(tom)
# 唔,果然輸出了我們自定義的內容
# >>> Your name is: tom
總結:在python中調用print()打印實例化對象時會調用__str__()函數,如果__str__()中有返回值,就會打印其中的返回值。
這個用法我是在刷題的時候看到的,來都來了那就賞你一道算法題吧,順便體會一下__str__函數的用途。
"""
Given a number n, generate all binary search trees that can be constructed with nodes 1 to n.
"""
# answer
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
result = str(self.value)
if self.left:
result = result + str(self.left)
if self.right:
result = result + str(self.right)
return result
def helper(low, high):
if low == high:
return [None]
result = []
for i in range(low, high):
left = helper(low, i)
right = helper(i + 1, high)
for l in left:
for r in right:
result.append(Node(i, l, r))
return result
def generate_bst(n):
# Fill this in.
return helper(1, n + 1)
for tree in generate_bst(4):
print(tree)
# Pre-order traversals of binary trees from 1 to n.
# 123
# 132
# 213
# 312
# 321
# 1 1 2 3 3
# \ \ / \ / /
# 2 3 1 3 1 2
# \ / \ /
# 3 2 2 1