如何调用和访问具有冒号分隔参数的函数的参数?

How to call and access arguments for a function that has colon separated parameters?

我正在尝试编写一个 python 函数来计算给定天数、小时数和分钟数的分钟数。

要调用的函数

def minutes(d:'days', h:'hours', m:'minutes'):

我对如何为 dhm 分配数值感到困惑,这样我就可以操纵这些变量。非常感谢任何帮助或建议。

函数正在使用 python3 function annotations:

您仍然可以像往常一样传递参数:

def minutes(d:'days', h:'hours', m:'minutes'):
    print(minutes.__annotations__ )
    print(d,h,m)
print(minutes(10,10,10)

{'d': 'days', 'm': 'minutes', 'h': 'hours'}
10 10 10

或者传递一条命令:

dic = {"d":22,"h":12,"m":25}
print(minutes(**dic))  
{'d': 'days', 'm': 'minutes', 'h': 'hours'}
22 12 25

可能是 namedtuplecollections 图书馆的一部分)的工作。 collections.namedtuple 允许您通过给定的名称访问元组的不同成员。

示例:

# import the namedtuple module from the library
from collections import namedtuple as nt
# create a type of namedtuple called Time that contains days, hours, minutes
Time = nt('Time', 'days hours minutes')
# you can make a Time instance this way
t1 = Time(0, 0, 1)
# now you can print it to see what's inside
print(t1) # Time(days=0, hours=0, minutes=1)
# ...and access the parts of the Time object by name
print(t1.minutes) # 1
# ...or access them by index
print(t1[2]) # 1

现在要转换为分钟,您只需这样做:

from collections import namedtuple as nt
Time = nt('Time', 'days hours minutes')
def minutes(d: 'days', h: 'hours', m: 'minutes'):
    t = Time(d, h, m)
    return t.days*24*60 + t.hours*60 + t.minutes

#testing
assert minutes(1,1,1) == 24*60 + 60 + 1

或者你也可以稍微改变一下你想要的函数签名,这样看起来更直接一些:

def minutes(t: 'time'):
    return t.days*24*60 + t.hours*60 + t.minutes

#testing
t = Time(1,1,1)
assert minutes(t) == 24*60 + 60 + 1

编辑:没有意识到问题的重点是了解冒号在做什么。函数签名中参数后面的冒号和字符串不是字典;他们是 function annotations,我相信这是 Python 3.

中的新内容