仅当传递的参数是字符串时,如何才能实例化 class?
How can I instantiate class only if argument passed is string?
我创建了一个 class '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)
在实例化对象之前检查参数的类型。还可以考虑使用 isinstance
来检查类型,而不是 type
class Stage:
def __init__(self, arg):
pass
if isinstance(str, entry):
obj = Stage(entry)
else:
raise TypeError('A str-type is required as an argument to the constructor')
您不能用该条件初始化对象,但可以抛出错误
class Stage:
def __init__(self, arg):
if not isinstance(arg, str):
raise TypeError("non-str value: %r was passed, str type argument required " % (arg,))
您也可以使用 classmethod
仅当传递的值为字符串时才创建实例:
class Stage:
def __init__(self, val):
self.val = val
@classmethod
def stage(cls, arg):
return None if not isinstance(arg, str) else cls(arg)
s = Stage.stage("name")
现在,如果 arg
是字符串,s
将是 Stage
的实例,如果 arg
是任何其他类型,则 None
将是 Stage
的实例。
我创建了一个 class '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)
在实例化对象之前检查参数的类型。还可以考虑使用 isinstance
来检查类型,而不是 type
class Stage:
def __init__(self, arg):
pass
if isinstance(str, entry):
obj = Stage(entry)
else:
raise TypeError('A str-type is required as an argument to the constructor')
您不能用该条件初始化对象,但可以抛出错误
class Stage:
def __init__(self, arg):
if not isinstance(arg, str):
raise TypeError("non-str value: %r was passed, str type argument required " % (arg,))
您也可以使用 classmethod
仅当传递的值为字符串时才创建实例:
class Stage:
def __init__(self, val):
self.val = val
@classmethod
def stage(cls, arg):
return None if not isinstance(arg, str) else cls(arg)
s = Stage.stage("name")
现在,如果 arg
是字符串,s
将是 Stage
的实例,如果 arg
是任何其他类型,则 None
将是 Stage
的实例。