简体   繁体   English

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

[英]Not creating an object when conditions are not met in python?

Is it possible to not create an object if certain conditions are not met in the constructor of a class? 如果在类的构造函数中不满足某些条件,是否可以不创建对象?

Eg: 例如:

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

a = ABC(3)
print(a)

This should print None (since it should not create an Object but return None in this case) but currently prints the Object... 这应该打印None (因为它不应该创建一个Object但在这种情况下返回None )但是当前打印Object ...

you can use a classmethod as an alternate constructor and return what you want: 你可以使用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

This code seems to show that an exception raised in an __init__() gives you the effect you want: 此代码似乎表明__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()

Output: 输出:

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

I think this shows the principle. 我认为这表明了原则。 Note that returning None is not returning a new object because None is a singleton in Python, but of course it is still an object. 请注意,返回None不会返回新对象,因为None是Python中的单例,但当然它仍然是一个对象。 Note also that __init__ will not be called as None is not an A class object. 另请注意, __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)

This outputs: 这输出:

<__main__.A object at 0x7f64e65c62e8>
None

With the help from @progmatico and a little try and error I managed to come to this solution: 在@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)

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

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