day17 物件導向作業

2021-10-13 09:59:47 字數 2458 閱讀 7129

定義乙個矩形類,擁有屬性:長、寬 擁有方法:求周長、求面積

class

rectangle

:def

__init__

(self, length, width)

: self.length = length

self.width = width

defperimeter

(self)

:return self.length*

2+ self.width*

2def

area

(self)

:return self.length*self.width

x1 = rectangle(10,

10)result = x1.perimeter(

)result2 = x1.area(

)print

('周長:'

, result,

'面積:'

, result2)

定義乙個二維點類,擁有屬性:x座標、y座標 擁有方法:求當前點到另外乙個點的距離

class

dot:

def__init__

(self, x, y)

: self.x = x

self.y = y

defdistance

(self, other)

:return

((self.x-other.x)**2

+(self.y-other.y)**2

)**0.5x1 = dot(0,

0)x2 = dot(3,

4)result = x1.distance(x2)

print

(result)

定義乙個圓類,擁有屬性:半徑、圓心 擁有方法:求圓的周長和面積、判斷當前圓和另乙個圓是否外切

class

circle

:def

__init__

(self, radius, x, y)

: self.radius = radius

self.x = x

self.y = y

defperimeter

(self)

:return2*

3.14

*self.radius

defarea

(self)

:return

3.14

*self.radius**

2def

excircle

(self, other)

:return

((self.x-other.x)**2

+(self.y-other.y))**

0.5== self.radius+other.radius

x1 = circle(5,

5,0)

x2 = circle(5,

15,0)

result1 = x1.perimeter(

)result2 = x1.area(

)result3 = x1.excircle(x2)

print

('周長:'

, result1,

'面積:'

, result2,

'是否是外切圓:'

, result3)

定義乙個線段類,擁有屬性:起點和終點, 擁有方法:獲取線段的長度

class

segment

:def

__init__

(self, x1, x2)

: self.x1 = x1

self.x2 = x2

deflength

(self)

:return

((self.x1 - self.x2)**2

)**0.5q1 = segment(10,

5)result = q1.length(

)print

(result)

定義乙個狗類和乙個人類:

狗擁有屬性:姓名、性別和品種 擁有方法:叫喚

人類擁有屬性:姓名、年齡、狗 擁有方法:遛狗

class dog:

def __init__(self, name, age, color, breed):

self.name = name

self.age = age

self.color = color

self.breed = breed

def __repr__(self):

return f'<>'

d2 = dog('小黃', '2', '黃色', '柯基')

print(d2)

Day17物件導向作業

定義乙個矩形類,擁有屬性 長 寬 擁有方法 求周長 求面積 class rectangle def init self,length,width self.length length self.width width defperimeter self return self.length self...

day17 物件導向作業

定義乙個矩形類,擁有屬性 長 寬 擁有方法 求周長 求面積 class rectangular def init self,x,y self.long x self.width y defcalculate self l self.long self.width 2 s self.long self...

day17 物件導向作業

定義乙個矩形類,擁有屬性 長 寬 擁有方法 求周長 求面積 class orthogon def init self,long 0 wide 0 self.long long self.wide wide defperimeter self print 周長 self.long self.wide ...