【问题标题】:Can I write python code that modifies itself during execution?我可以编写在执行期间修改自身的python代码吗?
【发布时间】:2018-05-16 08:30:02
【问题描述】:

我的意思是,

target_ZCR_mean = sample_dataframe_summary['ZCR'][1]
target_ZCR_std = sample_dataframe_summary['ZCR'][2]
lower_ZCR_lim = target_ZCR_mean - target_ZCR_std
upper_ZCR_lim = target_ZCR_mean + target_ZCR_std

target_RMS_mean = sample_dataframe_summary['RMS'][1]
target_RMS_std = sample_dataframe_summary['RMS'][2]
lower_RMS_lim = target_RMS_mean - target_RMS_std
upper_RMS_lim = target_RMS_mean + target_RMS_std

target_TEMPO_mean = sample_dataframe_summary['Tempo'][1]
target_TEMPO_std = sample_dataframe_summary['Tempo'][2]
lower_TEMPO_lim = target_TEMPO_mean - target_TEMPO_std
upper_TEMPO_lim = target_TEMPO_mean + target_TEMPO_std

target_BEAT_SPACING_mean = sample_dataframe_summary['Beat Spacing'][1]
target_BEAT_SPACING_std = sample_dataframe_summary['Beat Spacing'][2]
lower_BEAT_SPACING_lim = target_BEAT_SPACING_mean - target_BEAT_SPACING_std
upper_BEAT_SPACING_lim = target_BEAT_SPACING_mean + target_BEAT_SPACING_std

四行代码的每一块都非常相似,除了几个字符。

我是否可以编写一个函数、一个类或其他一些代码,这样我可以只将一个四行代码的模板包装到其中,并让它在运行时自行修改,以使代码完成上述工作代码...?

顺便说一下,我用的是python 3.6。

【问题讨论】:

  • 你能解释一下你想用这段代码实现什么吗?你只需要存储这些值吗?
  • 尝试装饰器,codementor.io/sheena/…
  • 不,您不能编写在执行期间修改自身的 Python 代码。但这无论如何都是错误的方法。使用数据结构来捕获规律,而不是尝试动态编写代码。就像 FHTMitchell 的解决方案一样。

标签: python self-modifying


【解决方案1】:

如果您发现自己存储了大量这样的变量,特别是如果它们是相关的,那么几乎可以肯定有更好的方法来做到这一点。动态修改源永远不是解决方案。一种方法是使用函数来保持重复的逻辑,并使用namedtuple 来存储结果数据:

import collections
Data = collections.namedtuple('Data', 'mean, std, lower_lim, upper_lim')

def get_data(key, sample_dataframe_summary):
     mean = sample_dataframe_summary[key][1]
     std = sample_dataframe_summary[key][2]
     lower_lim = mean - std
     upper_lim = mean + std
     return Data(mean, std, lower_lim, upper_lim)

zcr = get_data('ZCR', sample_dataframe_summary)
rms = get_data('RMS', sample_dataframe_summary)
tempo = get_data('Tempo', sample_dataframe_summary)
beat_spacing = get_data('Beat Spacing', sample_dataframe_summary)

然后您可以使用. 表示法访问数据,例如zcr.meantempo.upper_lim

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2021-01-02
    • 2015-11-03
    • 2013-12-15
    • 2023-04-02
    相关资源
    最近更新 更多