I didn't quite understand your question but to check if any variable is None
you can do an if
:
if A == None or B == None:
raise Exception
To raise an Exception when to instantiate a new object, just code the rule inside of __init__
method. This example considers that ClassA
and ClassB
have the same Parent, so for any child you can check if they have the same Parent:
def __init__(self, attr):
if not isinstance(attr, Parent):
raise Exception
Full example:
def main():
A = ClassA()
B = ClassB()
X = ClassX()
if A == None or B == None:
raise Exception
# Do not raise Exception
anotherClass = AnotherClass(A)
# Raise exception cause X doesn't inherit from Parent
anotherClass = AnotherClass(X)
class Parent(object):
pass
class ClassA(Parent):
pass
class ClassB(Parent):
pass
class ClassX(object):
pass
class AnotherClass(object):
def __init__(self, attr):
if not isinstance(attr, Parent):
raise Exception
if __name__ == '__main__':
main()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…