【问题标题】:Concatenate string to get a variable name Python [duplicate]连接字符串以获取变量名Python [重复]
【发布时间】:2020-07-09 15:56:27
【问题描述】:

我在 python 中有一个带有 3 个参数的函数:

def checkmsg(text, type, mac):

typema​​c 是我传递的 2 个变量,type 可以是 Alarms警告ma​​c12 所以我需要将 text 元素(它可以是单个元素或数组)存储在 status 变量中(我在一个类中有 4 个变量)

status.Alarms1, status.Alarms2, status.Warnings1, status.Warnings2

所以我需要首先检查 text 元素是否与 status 中的元素相同,如果不同则执行某些操作然后存储它, 所以我的问题是如何访问内容,而不是更新 status 变量的内容,必须从传递给函数的 2 变量中选择它?

附: (如果有帮助,我可以更改 status 4 变量的结构)

【问题讨论】:

  • 你的代码在哪里,你有什么问题?
  • 使用字典并以一个很酷的名称存储您的资料:mydict[(type,mac)]=text
  • 请在提问前添加您的代码,我们无法帮助您编写代码
  • 如果你真的想做,getattr(status, type + mac)

标签: python variables concatenation


【解决方案1】:

直接回答您的问题:

from dataclasses import dataclass


@dataclass
class Status:
    Alarms1: str
    Alarms2: str
    Warnings1: str
    Warnings2: str


status = Status(Alarms1="", Alarms2="", Warnings1="", Warnings2="")

def checkmsg(text, type_, mac):
    var = f"{type_}{mac}"
    old_text = getattr(status, var)
    if text != old_text:
        print(f"Setting {text} as new value of {var}")
        setattr(status, var, text)
    else:
        print(f"{var} is already set to {text}")

checkmsg("whatever", "Warnings", 1)
checkmsg("whatever more", "Alarms", 2)
checkmsg("whatever again", "Warnings", 1)
checkmsg("whatever more", "Alarms", 2)

运行时会打印出来

Setting whatever as new value of Warnings1
Setting whatever more as new value of Alarms2
Setting whatever again as new value of Warnings1
Alarms2 is already set to whatever more

但是,不要这样做。这是你不需要的黑魔法。使用字典存储您的状态。

【讨论】:

    猜你喜欢
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多