我想在更新密钥的值之前测试字典中是否存在密钥.我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
Run Code Online (Sandbox Code Playgroud)
我认为这不是完成这项任务的最佳方式.有没有更好的方法来测试字典中的密钥?
在测试变量有值时,是否有理由决定使用哪一个try或哪些if结构?
例如,有一个函数返回列表或不返回值.我想在处理之前检查结果.以下哪一项更可取,为什么?
result = function();
if (result):
for r in result:
#process items
Run Code Online (Sandbox Code Playgroud)
要么
result = function();
try:
for r in result:
#process items
except TypeError:
pass;
Run Code Online (Sandbox Code Playgroud)
我经常想检查对象是否有成员.一个例子是在函数中创建单例.为此,您可以这样使用hasattr:
class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
Run Code Online (Sandbox Code Playgroud)
但你也可以这样做:
class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
Run Code Online (Sandbox Code Playgroud)
另一种方法更好吗?
编辑:添加了@classmethod...但请注意,问题不是关于如何制作单例,而是如何检查对象中是否存在成员.
编辑:对于该示例,典型用法是:
s = Foo.singleton()
Run Code Online (Sandbox Code Playgroud)
然后s是类型的对象,Foo每次都相同.并且,通常,该方法被多次调用.