-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self,name,gender,breed): self.name = name self.gender = gender self.breed = breed def call_out(self): print(f'我是一只{self.gender}的{self.breed},我叫{self.name}') d = Dog('富贵','公','柴犬') d.call_out() class People: def __init__(self,names,age,dog): self.names = names self.age = age self.dog = dog def walk(self): print(f'我叫{self.names},今年{self.age},我要去遛{self.dog}') p = People('小明','12','富贵') p.walk()
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rect: def __init__(self,long,wide): self.long = long self.wide = wide def girth(self): print(f'周长为{self.wide*2+self.long*2}') def area(self): print(f'面积为{self.wide*self.long}') r = Rect(5,6) r.girth() r.area()
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Coordinate: def __init__(self,x1,y1,x2,y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def space(self): print(f'两点之间的距离为{((self.x1-self.x2)**2+(self.y1-self.y2)**2)**0.5}') c = Coordinate(0,0,3,3) c.space()
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: pi = 3.1415926 def __init__(self,r,x1,y1): self.r = r self.x1 = x1 self.y1 = y1 def girth(self): print(f'周长为{2*self.r*Circle.pi}') def area(self): print(f'面积为{Circle.pi * self.r ** 2}') def tangency(self,r1,x2,y2): self.r1 = r1 self.y2 = y2 self.x2 = x2 space = ((self.x1-self.x2)**2+(self.y1-self.y2)**2)**0.5 if space == self.r+self.r1 or space == abs(self.r-self.r1): return '相切' return '不相切' c = Circle(2,0,0) c.area() c.girth() print(c.tangency(2, 0, 4))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Segment: def __init__(self,x1,y1,x2,y2) -> int: self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def long(self): return ((self.x1-self.x2)**2+(self.y1-self.y2)**2)**0.5 s = Segment(0,0,0,3) print(s.long())
-
写一个斗地主游戏类(根据生活经验添加类的内容)
10-15
147
09-26
1074