Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a code snippet as following

A = a_class()
C= Another_Class(A)

B = b_class()
C = Another_Class(B)

I would like to check / raise errors when A or B is None or if Another_Class(X) when X is not A or B.

Thanks.

question from:https://stackoverflow.com/questions/66065860/how-to-check-if-a-constructor-is-assigned-initialized

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...