简体   繁体   English

阻止在Python构造函数中创建对象

[英]Prevent object from being created in Python constructor

How des one properly reject the creation of an object in a Python constructor? 如何正确拒绝在Python构造函数中创建对象? Consider an object: 考虑一个对象:

class Triangle:
    def __init__(self, a, b, c):
        sides = [a, b, c]
        sides.sort()
        if sides[0]+sides[1] < sides[2]:
            return None
        self._a = a
        self._b = b
        self._c = c

If the sides are not logical for a triangle, I would like to reject the creation of a Triangle object. 如果三角形的边不合逻辑,我想拒绝创建三角形对象。 Returning None does not prevent the creation of the Triangle object, and returning False throws an exception. 返回None不会阻止Triangle对象的创建,返回False会抛出异常。 What is the proper way to handle this? 处理这个问题的正确方法是什么? Should I throw some type of exception when the wrong parameters are given? 当给出错误的参数时,我应该抛出某种类型的异常吗?

Either raise an exception 提出异常

class Triangle:
    def __init__(self, a, b, c):
        sides = [a, b, c]
        sides.sort()
        if sides[0]+sides[1] < sides[2]:
            raise ValueError('invalid triangle!')
        self._a = a
        self._b = b
        self._c = c

or use an assert (which raises an exception itself) 或使用断言(自身引发异常)

class Triangle:
    def __init__(self, a, b, c):
        sides = [a, b, c]
        sides.sort()
        assert sides[0]+sides[1] >= sides[2]
        self._a = a
        self._b = b
        self._c = c

Which one is more appropriate depends on if throwing on invalid values is supposed to be part of your API (first version), or only to help find programmer errors (second version, as asserts will be skipped if you pass the -O "optimized" flag to the python interpreter). 哪一个更合适取决于抛出无效值是否应该是您的API(第一个版本)的一部分,或者仅仅是为了帮助查找程序员错误(第二个版本,因为如果您传递-O “优化”将跳过断言)标志到python解释器)。

Returning a value (even None ) from a constructor is not allowed 不允许从构造函数返回值(甚至是None

As you suggested, should raise an exception. 正如你的建议,应该提出异常。

class Triangle:
    def __init__(self, a, b, c):
        sides = [a, b, c]
        sides.sort()
        if sides[0]+sides[1] < sides[2]:
            raise ValueError()
        self._a = a
        self._b = b
        self._c = c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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