为了说明问题,我创建了一个简单的例子:
#!/usr/bin/env python
class Person():
def __init__(self):
self.cache = {}
def get_person_age(self):
def get_age():
print "Calculating age..."
return self.age
print self.cache
return self.cache.setdefault(self.name, get_age())
def set_person(self, name, age):
self.name = name
self.age = age
p = Person()
p.set_person('andrei', 12)
for k in range(0, 5):
p.get_person_age()
Run Code Online (Sandbox Code Playgroud)
我希望一旦设置了缓存,就不会再次调用函数get_person_age,但事实并非如此:
$ python cache_test.py
{}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
Run Code Online (Sandbox Code Playgroud)
一次又一次地调用函数.怎么了?
在Python 2.7中,str.format()接受非字符串参数并__str__在格式化输出之前调用值的方法:
class Test:
def __str__(self):
return 'test'
t = Test()
str(t) # output: 'test'
repr(t) # output: '__main__.Test instance at 0x...'
'{0: <5}'.format(t) # output: 'test ' in python 2.7 and TypeError in python3
'{0: <5}'.format('a') # output: 'a '
'{0: <5}'.format(None) # output: 'None ' in python 2.7 and TypeError in python3
'{0: <5}'.format([]) # output: '[] ' in python 2.7 and TypeError in python3
Run Code Online (Sandbox Code Playgroud)
但是当我传递一个datetime.time对象时,我' <5'在Python 2.7和Python 3中得到了输出:
from …Run Code Online (Sandbox Code Playgroud)