Day3

Meetalone發表於2024-04-14
# Exceptions
# try:
# num = int(input("input a number: "))
# except ValueError as ex:
# print(ex)
# else:
# print("continue")
# note: the type of ex is ValueError

# handling different type of exceptions
# there are some other types of exceptions like ZeroDivisionError, ValueError, etc.
# how to control different errors in one try blcok
# try:
# file1 = open("day3.py")
# age = int(input("Age: "))
# tmp = 10/age
# file1.close()
# except (ValueError, ZeroDivisionError) as ex:
# print(ex)
# else:
# print("continue")
# use finally clause to execute the last operation
# this piece of code above will be executed at the end of try block

# use "with" statement to make the code more readable and cleaner
# the with statement below is to automatically release external res
# try:
# with open("day3.py") as file1, open("day2.py") as file2:
# print("file open")
# except NameError as ex:
# print(ex)


# Class
# class attributes and instance attributes
# class attributes belong to all the instance of the class, they differ from instance attributes in that they are
# owned by one specific instance of the class and are not share between instances

# class methods and instance methods
# here method, draw, above is an instance method, we need an instance to call it, by contrast, we do not need an instance to call

# class Point:
# default_color = "red"

# def __init__(self, x, y):
# self.x = x
# self.y = y

# @classmethod
# def zero(cls):
# return cls(0, 0)

# def draw(self):
# print(f"({self.x},{self.y})")


# point = Point(1, 2)
# point = Point.zero()
# point.draw()


# Magic methods
# magic methods usually used for overloading the operators
# new words: under score '_'
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __str__(self):
return f"{self.x},{self.y}"

def __eq__(self, other):
return self.x == other.x and self.y == other.y


point = Point(1, 2)
print(str(point))

point1 = Point(1, 2)
print(point == point1)
# here we use "str()" to call magic method

相關文章