Is it possible to not create an object if certain conditions are not met in the constructor of a class?
E.g.:
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...
you can use a classmethod
as an alternate constructor and return what you want:
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With