练习(欸, 加深一下印象)
-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self, name:str, gender:str, type:str): self.name = name self.gender = gender self.type = type def jiaohuan(self): print('wang!wang!wang!') class Person: def __init__(self, name:str, age:int, dog:Dog): self.name = name self.age = age self.dog = dog def liugou(self): print(f""" ################### ##### /# 走你!欸,真不错!# ####### / ################### ##### |v| ############### || ####### \\\\ <-- name:{self.name} || ####### \\\\ <-- age:{self.age} || ####### \\\\ || ####### \\\\ / / \ \ ` / / \ \ ` / / \ \ ` ## / / \ \ ——#######`### <-- name:{dog.name} / / \ \ ####### <-- gender:{dog.gender} / / \ \ | | <-- type:{dog.type} """)
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: def __init__(self, lenght:float, width:float): self.length = lenght self.width = width def perimeter(self): return 2 * (self.length + self.width) def area(self): return self.length * self.width
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class TwoDimensional: def __init__(self, x:float, y:float): self.x = x self.y = y def distance(self, x:float, y:float): return ((self.x - x) ** 2 + (self.y - y) ** 2) ** 0.5
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
import math class Circle: def __init__(self, radius:float, circle_center:tuple): self.radius = radius self.center = circle_center def perimeter(self): return 2 * math.pi * self.radius def area(self): return math.pi * self.radius ** 2 def istangency(self, radius:float, circle_center:tuple): if ((self.center[0] - circle_center[0]) ** 2 + (self.center[-1] - circle_center[-1]) ** 2) ** 0.5 == self.radius + radius: return True else: return False
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self, strat_point:tuple, end_point:tuple): self.start_point = strat_point self.end_point = end_point def distance(self): return ((self.start_point[0] - self.end_point[0]) ** 2 + (self.start_point[-1] - self.end_point[-1]) ** 2) ** 0.5