使Python代码更有效地减小脚本大小?

时间:2019-04-12 16:04:39

标签: python firebase-realtime-database grovepi+

updated code我是Python的新手,正在尝试使我的代码更高效。目前,我正在将传感器值推送到Firebase Realtime数据库中的不同字段中,但是代码是重复的。无论如何,我可以使用循环或其他方法来减小脚本的大小。

def getSound():
    sound_value = grovepi.analogRead(sound_sensor)
    result = firebase.patch('/SoundValues/Monday/'{'Sound1':int(sound_value)})
    print("the sound value is%d" %sound_value)
    time.sleep(1)

def getSound1():
    sound_value = grovepi.analogRead(sound_sensor)
    result = firebase.patch('/SoundValues/Monday/'{'Sound2':int(sound_value)})
    print("the sound value is%d" %sound_value)
    time.sleep(1)

任何帮助将不胜感激:-)

2 个答案:

答案 0 :(得分:1)

更改功能,使其接受声音编号作为参数:

def getSound(number):
    sound_value = grovepi.analogRead(sound_sensor)
    key = 'Sound%d' % number # this will be 'Sound1', 'Sound2', etc.
    result = firebase.patch('/SoundValues/Monday/'{key :int(sound_value)})
    print("the sound value is%d" %sound_value)
    time.sleep(1)

然后,您将函数调用为getSound(1)getSound(2)等。

答案 1 :(得分:0)

我将始终查看getSound()和getSound1()之间的区别。 看起来这些函数具有完全相同的代码,除了以下行:

result = firebase.patch('/SoundValues/Monday/'{'Sound1':int(sound_value)})

因此,您可以使用所有重复代码编写单个函数,并将“ sound_spec”用作函数的参数。看起来像这样:

sound_value = grovepi.analogRead(sound_sensor)

def getSound(sound_spec):
    result = firebase.patch(sound_spec)
    print("the sound value is%d" %sound_value)
    print("firebase.path result %s" % str(result))
    time.sleep(1)

然后,您可以获取“ sound_specification”列表,并使用for循环获取多个值的结果:

sound_specs = ['/SoundValues/Monday/'{'Sound1':int(sound_value)},'/SoundValues/Monday/'{'Sound2':int(sound_value)}]

for sound_spec in sound_specs:
    getSound(sound_spec)