如何在 Python 中中止对象实例的创建? [英] How do I abort object instance creation in Python?

查看:59
本文介绍了如何在 Python 中中止对象实例的创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个类,该类将根据传递给类的参数的值在实例创建期间中止.我尝试了一些事情,其中​​之一是在 __new__ 方法中引发错误:

class a():def __new__(cls, x):如果 x == 真:返回 cls别的:引发值错误

这就是我希望发生的事情:

>>obj1 = a(True)>>obj2 = a(假)ValueError 回溯(最近一次调用)

obj1 存在但 obj2 不存在.

有什么想法吗?

解决方案

当你覆盖__new__时,不要忘记调用super!

<预><代码>>>>类测试(对象):... def __new__(cls, x):...如果 x:... return super(Test, cls).__new__(cls)... 别的:... 引发 ValueError...>>>obj1 = 测试(真)>>>obj2 = 测试(假)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 6 行,在 __new__ 中值错误>>>对象1<__main__.Test object at 0xb7738b2c>>>>对象2回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中NameError: 名称 'obj2' 未定义

在创建实例是你的工作时,简单地返回类没有任何作用.这就是超类的 __new__ 方法所做的,所以好好利用它.

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 an error in the __new__ method:

class a():
    def __new__(cls, x):
        if x == True:
            return cls
        else:
            raise ValueError

This is what I was hoping would happen:

>>obj1 = a(True)
>>obj2 = a(False)
ValueError Traceback (most recent call last)

obj1 exists but obj2 doesn't.

Any ideas?

解决方案

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 "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __new__
ValueError
>>> obj1
<__main__.Test object at 0xb7738b2c>
>>> obj2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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.

这篇关于如何在 Python 中中止对象实例的创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆