1.首先要明白题的意思:
1️⃣构造一个类名为:Foo
2️⃣实现: pring(Foo().think.different.better) 打印为: think different better
3️⃣用python魔法方法实现
2. 分析:只要明白上面的题意,然后清楚魔法方法,便可以清晰自己的思路.(如果不明白魔法方法自行百度)
3. 实现
#coding:utf8
class Foo(object):
def __init__(self):
pass
def __getattr__(self, item):
print(item+" ",end="")
return self
def __str__(self):
return ""
print(Foo().think.different.better)
由以上代码可以看出,只要了解__getAttr__和__str__方法,这道题可以轻松解决.
4. 如有问题,请留言.
5.补充: Foo()点调用属性的流程.
#coding:utf8
class Foo(object):
def __init__(self):
self.better = "ok"
# def __getattr__(self, item):
# print(item+" ",end="")
# return self
def __getattribute__(self, item):
return self.name
def __str__(self):
return ""
print(Foo().think.different.better)
执行报错如下:
/Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/bin/python /Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/include/test/GetAttr.py
Traceback (most recent call last):
File "/Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/include/test/GetAttr.py", line 17, in <module>
print(Foo().think.different.better)
File "/Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/include/test/GetAttr.py", line 12, in __getattribute__
return self.name
File "/Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/include/test/GetAttr.py", line 12, in __getattribute__
return self.name
File "/Users/wangxiaowei/Downloads/pycharmWorkSpace/Demo01/venv/include/test/GetAttr.py", line 12, in __getattribute__
return self.name
[Previous line repeated 329 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
Foo().think,当进行点调用的时候: 首先会调用Foo类的 __getattribute__方法. 而__getattr__方法只不过是__getattribute__方法的一小组成部分而已. 所以,我们使用__getattribute__也可以完成上述问题. 那么为什么不适用他呢?
因为: 如果__getattribute__方法使用不当,会很容易陷入递归,死循环之中,直到达到python最大深度调用然后以报错而终.
扫描二维码关注公众号,回复:
2358909 查看本文章
具体原因如下:
def __getattribute__(self, item):
return self.name
乍一看之下,Foo()点调用上面方法,他应该是返回"ok"字符串给我们. 但是其中没有这么简单!
在 return self.name 中, self相当于Foo()对象,那么:
* [self.name]就相当于是[Foo().__getattribute__(self, "OK")],
在方法体内调用方法本身,会造成递归调用,如果在递归调用中没有可以使其结束递归循环的语句.那么因为python存在最大深度调用的问题.当达到该阈值以后,程序就会以报错结束.
所以,一般我们不是在个别需要的时候,一般不对__getattribute__方法进行重写操作.