我创建了一个类 '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/