- 定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle:
def __init__(self, chang, kuan):
self.chang = chang
self.kuan = kuan
def zhouchang(self):
return (self.chang + self.kuan) * 2
def area(self):
return self.chang * self.kuan
r1 = Rectangle(2, 3)
print(r1.zhouchang())
print(r1.area())
- 定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point:
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self):
return ((self.x - Point.x) ** 2 + (self.y - Point.y) ** 2) ** 0.5
p1 = Point(1, 2)
print(p1.distance())
- 定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Yuan:
pi = 3.14
x = 3
y = 4
r = 5
def __init__(self, x, y, r=0):
self.x = x
self.y = y
self.r = r
def zhouchang(self):
return 2 * Yuan.pi * self.r
def area(self):
return Yuan.pi * self.r ** 2
def if_wq(self):
distance = ((self.x - Yuan.x) ** 2 + (self.y - Yuan.y) ** 2) ** 0.5
r_dis = Yuan.r + self.r
if distance == r_dis:
return True
else:
return False
y1 = Yuan(4, 5, 3)
print(y1.zhouchang())
print(y1.area())
print(y1.if_wq())
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Xianduan: def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d def length(self): return ((self.a - self.c) ** 2 + (self.b - self.d) ** 2) ** 0.5 p1 = Xianduan(0, 0, 1, 1) print(p1.length())