Last active
July 20, 2017 07:36
-
-
Save Zheaoli/fffac4277a73ba98b042df38ebb53805 to your computer and use it in GitHub Desktop.
经典面试题解析
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo(): | |
def __init__(self): | |
self._temp_list=[] | |
def __getattr__(self,name): | |
self._temp_list.append(name) | |
return self | |
def __str__(self): | |
return " ".join(self._temp_list) | |
# 这道题这样几个知识点 | |
# 首先看题,print(Foo().think.different) 调用完后一次性输出 think different | |
# 第一个点,链式调用,于是知道这个地方需要修改 __getattr__ 方法,每次需要返回 self 迭代 | |
# 第二个点,这个题因为是在调用完后,一次性输出,所以,需要一个 list 记录调用记录,于是可以再 __init__ 里初始化一个 | |
# 第三个点,停止调用后,需要在一个函数里把list里面的数据format成一个字符串,于是我们要考虑到一个实例被print调用时,__str__ 方法会被触发 | |
print(Foo().think.different) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment