How do I abort object instance creation in Python?

前端 未结 2 2057
自闭症患者
自闭症患者 2021-02-05 03:30

I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I\'ve tried a few things, one of them being raising

2条回答
  •  耶瑟儿~
    2021-02-05 04:21

    When you override __new__, dont forget to call to super!

    >>> class Test(object):
    ...     def __new__(cls, x):
    ...         if x:
    ...             return super(Test, cls).__new__(cls)
    ...         else:
    ...             raise ValueError
    ... 
    >>> obj1 = Test(True)
    >>> obj2 = Test(False)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 6, in __new__
    ValueError
    >>> obj1
    <__main__.Test object at 0xb7738b2c>
    >>> obj2
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'obj2' is not defined
    

    Simply returning the class does nothing when it was your job to create an instance. This is what the super class's __new__ method does, so take advantage of it.

提交回复
热议问题