[英]How can I instantiate class only if argument passed is string?
I created a class 'Stage' and want instantiate it only if argument passed to init (arg) 我创建了一个'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
Raise an exception: 引发异常:
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
However, consider whether it the value really needs to be a str
, or just something that can be turned into a str
: 然而,考虑该值是否真的需要一个str
,或只是一些可以变成一个str
:
def __init__(self, arg):
arg = str(arg)
# ...
If you want to avoid creating the instance altogether, you need to override __new__
, not __init__
(with some of the previous advice folded in): 如果要避免完全创建该实例,则需要重写__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)
Check for the type of argument before instantiating your object. 在实例化对象之前检查参数的类型。 Also consider using isinstance
to check for a type, instead of type
还考虑使用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')
You cannot initialize an object with that condition, but you can throw an error 您不能使用该条件初始化对象,但是会引发错误
class Stage:
def __init__(self, arg):
if not isinstance(arg, str):
raise TypeError("non-str value: %r was passed, str type argument required " % (arg,))
You can also use a classmethod
to create an instance only if the passed value is a string: 您还可以使用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")
Now, s
will either be instance of Stage
if arg
is a string or None
if arg
is any other type. 现在,如果arg
是字符串,则s
将是Stage
实例;如果arg
是任何其他类型,则s
将是None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.