是否可以使用相同的数据类型从函数返回,还是分配默认值?还是没有?什么是更好的编码实践,为什么?
例如.python中的一些伪代码:
/ 1
def my_position(): # returns a positive integer if found
if(object is present):
position = get_position()
return position # eg 2,3,4,6
else:
return None # or return -1 or 0 ??
Run Code Online (Sandbox Code Playgroud)
/ 2
def get_database_rows():
do query to whatever database
if(rows are found):
return [list of rows]
else:
return None # or return empty list [] ?
Run Code Online (Sandbox Code Playgroud)
/ 3
the_dictionary = {'a' : 'john','b':'mike','c': 'robert' } # values are names i.e. non empty string
my_new_var = the_dictionary.get('z', None) # or the_dictionary.get('z','') ?
Run Code Online (Sandbox Code Playgroud)
IndexError如果找不到该项,则提高.这就是Python的list功能.(或者在执行二分查找或类似操作时,可能返回项目应该存在的索引.)
从逻辑上考虑你的函数做什么:如果它返回满足某个条件的数据库中所有项目的列表,并且没有这样的项目,那么返回一个空列表是有意义的,因为它允许所有常用的列表操作(len,in)无需显式检查即可运行.
但是,如果缺少必需的项目表示不一致,则提出异常.
我之前的评论特别适用于这种情况:它取决于你将如何处理你得到的价值.普通的dict只是KeyError在找不到钥匙时提出.您正在用值替换该异常,因此您应该知道在程序的上下文中哪个值有意义.如果没有值,那么就让异常飞起来.
也就是说,返回None往往是一个坏主意,因为它可能会掩盖错误.None是Python中的默认返回值,因此返回它的函数可能只表示其作者忘记了一个return语句:
def food(what):
if what == HAM:
return "HAM!"
if what == SPAM:
return " ".join(["SPAM" for i in range(10)])
# should raise an exception here
lunch = food(EGGS) # now lunch is None, but what does that mean?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1135 次 |
| 最近记录: |