简体   繁体   中英

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)

#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 :

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):

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM