Basic Python Learning--class and exception

 

class Cat:
    def __init__(self, name):
        print("__init__")
        self.gender = "male"
        self.age = 2
        self.color = "orange"
        self.name = name

    def __enter__(self):
        print("__enter__")
        return self

    def bug_cat1_broken_eye(self):
        raise Exception(10)

    def bug_cat2_broken_leg(self):
        raise Exception("broken leg")
        print("after raise Exception")

    def speak(self):
        print(self.name, end=" ")
        print("miao miao miao")

    def run(self):
        print(self.name, end=" ")
        print("quietly and fast")

    def how_old_am_i(self, age):
        if self.age == age:
            print("bingo")
            return
        for i in range(10):
            new_age = int(input("try again"))
            if new_age == self.age:
                print("bingo")
                return
        else:
            print("sorry")
            return

    def __exit__(self, exc_type, exc_val, exc_tb):

        print("__exit__")
        print("type:", end="")
        print(exc_type)
        print("val:", end="")
        print(exc_val)
        print("trace:", end="")
        print(exc_tb)

    def __del__(self):
        print("__del__")
        print(self.name, end=" ")
        print("was deleted")


def test_except():
    xixi = Cat("xixi")
    xixi.bug_cat1_broken_eye()
    print("after xixi.bug_cat1_broken_eye()")


def test_test_except():
    try:
        test_except()
    except Exception as e:
        print("test_test_except ", e)
        raise Exception(e)
    print("after test_except()")


try:
    test_test_except()
except Exception as e:
    print("except Exception bottom", e)

你可能感兴趣的:(python)