【问题标题】:Type mutations work strange in python, why? [closed]类型突变在 python 中很奇怪,为什么? [关闭]
【发布时间】:2020-07-25 02:23:16
【问题描述】:

我需要对输入变量的正确变量类型进行简单检查。所以我做了这样的功能:

def is_good_value(some_value, value_type="numeric"):
        """Check if value is of right type"""

        allowed_types = {
            "numeric" : [float, int],
            "string"  : [str],
            "file"    : [os.path.isfile]
        }

        for each_type in allowed_types[value_type]:
            try:
                each_type(some_value)
            except: exit(print(f"Wrong type: {some_value}, should be {allowed_types[value_type]}"))

如果我尝试检查:

is_good_value("1")

我得到了例外。显然,这是因为我传递了字符串“1”。

但是,如果我使 int("1")float("1") 突变一切都很好,因为这个值可以转换为这些类型。

如何修改我的 def 以获得与简单变异操作相同的结果?

【问题讨论】:

  • 从您的问题中不清楚您要在这里做什么。您想知道给定的字符串是否可以转换为数字吗?
  • 你描述的不是我从这段代码中看到的。我认为它需要更基本的调试。它只是失败并返回 None 因为你没有 return 声明。
  • 另外,我想你可以不将'1' 检测为字符串。

标签: python mutation


【解决方案1】:

听起来您正在寻找 isinstance(和 isfile 用于该文件案例)...

allowed_types = {
    "numeric": lambda v: isinstance(v, (float, int)) and not isinstance(v, bool),
    "string": lambda v: isinstance(v, str),
    "file": os.path.isfile,
}
def is_good_value(some_value, value_type="numeric"):
    return allowed_types[value_type](some_value)

【讨论】:

  • 不明白你的意思。如果vstr(1) 那么isinstance(v, (int,)) 不会返回True。
  • 好吧,说句公道话,OP的目标也不是很清楚:)
  • 你是对的...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 2019-12-19
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多