将关键字作为参数传递

2024-05-29 02:39:04 发布

您现在位置:Python中文网/ 问答频道 /正文

将关键字作为函数参数是否有违Python的“风格”? e、 g

def findStartTime(dict):
  for key, value in dict.iteritems():
    #do something based on values in dictionary
  return something

…除了风格,
是否会出现任何潜在的问题?你知道吗


Tags: keyinforvalue风格ondef关键字
2条回答

如果将来出于某种原因,您想在函数中调用dict()来创建字典呢?无论如何,给变量起个有意义的名字,而不是按类型命名。你知道吗

这个问题可归结为范围问题。如果调用某个dict,则无法访问dict方法。你知道吗

例如,如果调用变量math,则无法访问math.method()

>>> import math
>>> math = "MATH"
>>> rounded_number = math.floor(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'floor'
>>> import math
>>> rounded_number = math.floor(3.14)
>>> rounded_number
3.0

所以我导入数学,然后用字符串重写模块。因此AttributeError

然后我重新导入math和boom,math.floor()又是一个有效的方法。所以基本上,如果调用dict“dict”,它将阻止使用dict()构造函数和其他方法。你知道吗

希望这有帮助!你知道吗

相关问题 更多 >

    热门问题