生成动态时间增量:python
这是我的情况:
import foo, bar, etc
frequency = ["hours","days","weeks"]
class geoProcessClass():
def __init__(self,geoTaskHandler,startDate,frequency,frequencyMultiple=1,*args):
self.interval = self.__determineTimeDelta(frequency,frequencyMultiple)
def __determineTimeDelta(self,frequency,frequencyMultiple):
if frequency in frequency:
interval = datetime.timedelta(print eval(frequency + "=" + str(frequencyMultiple)))
return interval
else:
interval = datetime.timedelta("days=1")
return interval
我想用 timedelta
动态定义时间间隔,但这似乎不起作用。
有什么具体方法可以使这项工作有效吗?我在这里得到无效语法。
还有更好的方法吗?
Here's my situation:
import foo, bar, etc
frequency = ["hours","days","weeks"]
class geoProcessClass():
def __init__(self,geoTaskHandler,startDate,frequency,frequencyMultiple=1,*args):
self.interval = self.__determineTimeDelta(frequency,frequencyMultiple)
def __determineTimeDelta(self,frequency,frequencyMultiple):
if frequency in frequency:
interval = datetime.timedelta(print eval(frequency + "=" + str(frequencyMultiple)))
return interval
else:
interval = datetime.timedelta("days=1")
return interval
I want to dynamically define a time interval with timedelta
, but this does not seem to work.
Is there any specific way to make this work? I'm getting invalid syntax here.
Are there any better ways to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
func(**kwargs)
之类的语法调用带有动态参数的函数,其中kwargs
是命名参数的名称/值映射的字典。我还将全局
频率
列表重命名为频率
,因为ifFrequencyinFrequency
这一行没有多大意义。不管它的价值如何,从风格上来说,默默地纠正调用者所犯的错误通常是不受欢迎的。如果呼叫者用无效的参数给你打电话,你可能应该立即大声失败,而不是试图继续喋喋不休。我建议不要使用
if
语句。有关可变长度和关键字参数列表的更多信息,请参阅:
You can call a function with dynamic arguments using syntax like
func(**kwargs)
wherekwargs
is dictionary of name/value mappings for the named arguments.I also renamed the global
frequency
list tofrequencies
since the lineif frequency in frequency
didn't make a whole lot of sense.For what it's worth, stylistically it's usually frowned upon to silently correct errors a caller makes. If the caller calls you with invalid arguments you should probably fail immediately and loudly rather than try to keep chugging. I'd recommend against that
if
statement.For more information on variable-length and keyword argument lists, see:
您对 print eval(...) 的使用看起来有点过于复杂(正如您提到的,这是错误的)。
如果您想将关键字参数传递给函数,只需这样做:
不过,我没有看到名为
Frequency
的关键字参数,因此这可能是一个单独的问题。Your use of
print eval(...)
looks a bit over-complicated (and wrong, as you mention).If you want to pass a keyword argument to a function, just do it:
I don't see a keyword argument called
frequency
though, so that might be a separate problem.