仅当传递的参数为字符串时,才能实例化类吗?

时间:2019-05-17 12:23:27

标签: 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

4 个答案:

答案 0 :(得分:2)

引发异常:

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)

答案 1 :(得分:1)

在实例化对象之前检查参数的类型。还可以考虑使用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')

答案 2 :(得分:1)

您不能使用该条件初始化对象,但是会引发错误

class Stage:
    def __init__(self, arg):
        if not isinstance(arg, str):
            raise TypeError("non-str value: %r was passed, str type argument required " % (arg,))

答案 3 :(得分:0)

仅当传递的值为字符串时,您也可以使用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")

现在,如果s是字符串,则Stage将是arg的实例,如果None是任何其他类型,则arg将是dispatch()