在python中不满足条件时不创建对象?

时间:2017-12-14 18:15:48

标签: python python-3.x class

如果在类的构造函数中不满足某些条件,是否可以不创建对象?

E.g:

class ABC:
    def __init__(self, a):
        if a > 5:
            self.a = a
        else:
            return None

a = ABC(3)
print(a)

这应该打印None(因为它不应该创建一个Object但在这种情况下返回None)但是当前打印了Object ...

4 个答案:

答案 0 :(得分:3)

您可以使用classmethod作为替代构造函数并返回您想要的内容:

class ABC:
    def __init__(self, a):
        self.a = a

    @classmethod
    def with_validation(cls, a):
        if a > 5:
            return cls(a)
        return None


a = ABC.with_validation(10)

a
<__main__.ABC at 0x10ceec288>

a = ABC.with_validation(4)

a

type(a)
NoneType

答案 1 :(得分:2)

此代码似乎表明__init__()中引发的异常会为您提供所需的效果:

class Obj:
    def __init__(self):
        raise Exception("invalid condition")

class E:
    def __call__(self):
        raise Exception("raise")

def create(aType):
    return aType()

def catchEx():
    e = E()
    funcs=[Obj, int, e]

    for func in funcs:
        try:
            func()
            print('No exception:', func)
        except Exception as e:
            print(e)

catchEx()

输出:

invalid condition
No exception: <class 'int'>
raise

答案 2 :(得分:2)

我认为这表明了原则。请注意,返回 IE.Visible = true; System.Threading.Thread.Sleep(500); 并不返回新对象,因为None是Python中的单例,但当然它仍然是一个对象。另请注意,None不会被调用,因为__init__不是None类对象。

A

输出:

class A():
    def __new__(cls, condition):
        if condition:
            obj = super().__new__(cls)
            return obj

a = A(True)
print(a)
a1 = A(False)
print(a1)

答案 3 :(得分:1)

在@progmatico的帮助下,我尝试了一点点尝试和错误:

class ABC:
    def __new__(cls, *args, **kwargs):
        if len(args) > 0:
            arg = args[0]
        else:
            arg = kwargs['a']

        if arg <= 5:
            return None
        return object.__new__(cls)

    def __init__(self, a):
        self.a = a

    def __str__(self):
        return str(self.a)

a = ABC(a=3)
print(a)
b = ABC(a=7)
print(b)