小编Ale*_*äck的帖子

为什么setdefault在设置密钥时会评估默认值?

为了说明问题,我创建了一个简单的例子:

#!/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 setdefault

5
推荐指数
1
解决办法
279
查看次数

将datetime对象传递给str.format()时出现意外结果

在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)

python datetime

2
推荐指数
1
解决办法
141
查看次数

标签 统计

python ×2

datetime ×1

setdefault ×1