from math import pi
1. 定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle:
def __init__(self, long, wide):
self.a = long
self.b = wide
def Perimeter(self):
return (self.a + self.b) * 2
def acreage(self):
return self.a * self.b
p1 = Rectangle(20, 30)
print(p1.Perimeter())
2. 定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, other):
# self=p1, other=p2
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
# p1 = Point(30, 40)
# p2 = Point()
# print(p1.distance(p2))
3. 定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle:
pi = 3.1415926
def __init__(self, radius, center=Point(0, 0)):
self.radius = radius
self.center = center
def perimeter(self):
return 2*Circle.pi*self.radius
def area(self):
return Circle.pi * self.radius ** 2
def is_exterior_contact(self, other):
return self.center.distance(other.center) == self.radius+other.radius
c1 = Circle(10)
c2 = Circle(20, Point(40, 0))
print(c1.is_exterior_contact(c2))
4. 定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line:
def __init__(self, start: Point, end: Point):
self.start = start
self.end = end
def length(self):
return self.start.distance(self.end)
l1 = Line(Point(0, 0), Point(100, 100))
print(l1.length())
5. 定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog:
def __init__(self, name, gender='母狗', breed='土狗'):
self.name = name
self.gender = gender
self.breed = breed
def bark(self):
print('汪汪汪!')
class Person:
def __init__(self, name, age=18, dog=None):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
if self.dog:
print(f'{self.name}牵着{self.dog.name}散步!')
else:
print(f'{self.name}没有狗!')
p1 = Person('小明')
p2 = Person('小花')
p1.dog = Dog('大黄')
p1.walk_the_dog()
p2.walk_the_dog()
day17-面向对象作业
最新推荐文章于 2024-03-06 19:44:34 发布