python - 仅当传递的参数是字符串时,如何才能实例化类?

标签 python class instance

我创建了一个类 'Stage' 并希望仅在参数传递给 init(arg) 时实例化它

#example code

class Stage:
    def __init__(self, arg):
        if type(arg) == str:
            #create object
        else:
            #do not create object

#main:
# entry = input()

obj = Stage(entry)

if obj:
    print("created")         # if entry is string
else:
    print("not created")     # if entry is float

最佳答案

引发异常:

def __init__(self, arg):
    if not isinstance(arg, str):
        raise TypeError("Stage.__init__ called with a non-str value: %r" % (arg,))

    # continue initializing the object

但是,请考虑值是否真的需要 str,或者只是可以变成 str 的东西:

def __init__(self, arg):
    arg = str(arg)
    # ...

如果你想完全避免创建实例,你需要覆盖__new__,而不是__init__(折叠之前的一些建议在):

class Stage:
    def __new__(cls, arg):
        try:
            arg = str(arg)
        except ValueError:
            raise TypeError("Could not convert arg to str: %r" % (arg, ))

        return super().__new__(cls, arg)

关于python - 仅当传递的参数是字符串时,如何才能实例化类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56186370/

相关文章:

class - 从字符串创建 React 类的实例

php - 在 PHP 中获取对象的实例 ID

python - 删除相似数据

python - 使用子进程python获取命令行执行抛出的错误

class - 对象初始化器 + 属性初始化器(从 C# 到 F#)

c++ - 虚拟类多重继承

java - 访问动态生成的 GUI JTextField 对象

python - 上个月日期时间 Pandas

python - 如何消除反斜杠后的空格(Python 3.4)

c++ - 我必须在类的头文件中提及私有(private)方法吗?