-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: def __init__(self, length1=0, weight1=0): self.length = length1 self.weight = weight1 def area(self): print('面积为:', self.length * self.weight) def perimeter(self): print('周长为:', (self.length+self.weight) * 2) r1 = Rectangle(10, 20) r2 = Rectangle(10, 100) r1.area() # 面积为: 200 r1.perimeter() # 周长为: 60 r2.area() # 面积为: 1000 r2.perimeter() # 周长为: 220
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: def __init__(self, x, y): self.x = x self.y = y def distance_point(self, other): distance = ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5 return distance p1 = Point(3, 4) p2 = Point(10, 10) p1.distance_point(p2)
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: pai = 3.14 def __init__(self, r, center: Point): self.r = r self.center = center def perimeter(self): print(self.pai * self.r * 2) def area(self): print(self.pai * self.r ** 2) def tan(self, other_circle): return self.center.distance_point(other_circle.center) == self.r + other_circle.r c1 = Circle(1, Point(0, 0)) c2 = Circle(1, Point(2, 0)) print(c1.tan(c2))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self, start: Point, end: Point): self.start = start self.end = end def long(self): return self.start.distance_point(self.end) l1 = Line(Point(0, 0), Point(2, 0)) print(l1.long())
-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog:
def __init__(self, name1, sex1, variety1):
self.name = name1
self.sex = sex1
self.variety = variety1
def call(self):
print(f'{self.name}正在称唤')
class Person:
def __init__(self, name, age, dog: Dog):
self.name = name
self.age = age
self.dog = dog
def walk(self):
if self.dog:
print(f'{self.name}正在遛{self.dog.name}')
else:
print('你还没有狗')
dog1 = Dog('小花', '雌', '泰迪')
p1 = Person('小明', 18, dog1)
dog1.call()
p1.walk()