day18-面向对象作业
作者:互联网
-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
class Dog: """一个狗的类""" def __init__(self, name, variety, gender='公'): self.name = name self.gender = gender self.variety = variety def __repr__(self): return str(self.__dict__) def cry_dog(self): """叫唤名字,狗就会旺旺旺""" return f"{self.name},我旺不旺\n旺旺旺" dog = Dog('旺财', '中华田园犬') print(dog) print(dog.cry_dog())
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Person: """人的类""" def __init__(self, name, age): self.name = name self.age = age self.dog1 = dog def __repr__(self): return str(self.__dict__) def walk_the_dog(self): """遛狗""" return f'{dog.name} 速度过来' person = Person('睿睿', '28') print(person) print(person.walk_the_dog())
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: """一个矩形类""" def __init__(self, long, wide): self.long = long self.wide = wide def perimeter(self): """求周长""" return f'周长为:{(self.wide + self.long) * 2}' def area(self): """求面积""" return f'面积为:{self.long * self.wide}' rectangle = Rectangle(10, 10) print(rectangle.perimeter()) print(rectangle.area())
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Coordinates: """定义一个二维点类""" def __init__(self, x, y): self.x = x self.y = y def distance(self): """求x到y的距离""" return f'求x到y的距离为:{(self.x ** 2 + self.y ** 2) ** 0.5:.2f}' coordinates = Coordinates(-1234, 5678) print(coordinates.distance())
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: """一个圆类""" pi = 3.141592653 def __init__(self, r, x_label): self.r = r self.x_label = x_label def area(self): """ 计算圆面积""" return '半径为:{self.r}时,面积:{P.pi * self.r ** 2 :.2f}' def perimeter(self): """ 计算圆周长""" return '半径为:{self.r}时,周长:{2 * P.pi * self.r:.2f}' def exterior_contact(self, r1, x1, y1): """判断当前圆和另一个圆是否外切""" if ((self.x_label[0] - x1) ** 2 + (self.x_label[-1] - y1) ** 2) ** 0.5 == self.r + r1: return '是外切' else: return '非外切' c1 = Circle(61, [1, 1]) print(c1.exterior_contact(60, 1, 122))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class LineSegment: """一个线段类""" def __init__(self, origin, destination): self.origin = origin self.destination = destination def length(self): return self.destination - self.origin lineSegment = LineSegment(2345, 4567890) print(lineSegment.length())
标签:__,return,self,作业,dog,面向对象,print,day18,def 来源: https://blog.csdn.net/eeffve/article/details/122095399