-
Define a rectangle class with attributes: length and width. Methods: find perimeter and area
class Rectangle: def __init__(self, length=0, wide=0): self.length = length self.wide = wide def perimeter(self): return (self.length+self.wide)*2 def acreage(self): return self.length*self.wide r1 = Rectangle(4, 5) print(r1.perimeter(), r1.acreage())
-
Define a two-dimensional point class with attributes: x-coordinate and y-coordinate. Method: find the distance from the current point to another point
class Piont: def __init__(self, x=0, y=0): self.x = x self.y = y def p_to_p_length(self, point): return ((self.x-point.x)**2+(self.y-point.y)**2)**0.5 p1 = Piont(2, 5) p2 = Piont(-1, 1) print(p1.p_to_p_length(p2))
-
Define a circle class with attributes: radius and center. Methods: find the circumference and area of the circle, determine whether the current circle is circumscribed to another circle
import math class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def p_to_p_length(self, point): return ((self.x-point.x)**2+(self.y-point.y)**2)**0.5 class Circle: def __init__(self, radius=0, center=Point(0, 0)): self.radius = radius self.center = center def perimeter(self): return 2*math.pi*self.radius def acreage(self): return self.radius**2*math.pi def exterior_contact(self, another): return self.radius+another.radius == self.center.p_to_p_length(another.center) c1 = Circle(1, Point(0, 0)) c2 = Circle(4, Point(3, 4)) print(c1.perimeter(), c1.acreage(), c1.exterior_contact(c2))
-
Define a line segment class, with attributes: start point and end point, and method: get the length of the line segment
class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def p_to_p_length(self, point): return ((self.x-point.x)**2+(self.y-point.y)**2)**0.5 class Line: def __init__(self, start: Point, end: Point): self.start = start self.end = end def length(self): return self.start.p_to_p_length(self.end) l1 = Line(Point(0, 0), Point(3, 4)) print(l1.length())
-
Define a dog and a human:
Dog has attributes: name, gender and breed. Method of possession: call
Human possessing attributes: name, age, dog possessing method: walking the dog
class Human: def __init__(self, name: str, age: int, dog=None): self.name = name self.age = age self.dog = dog def walk_the_dog(self): if self.dog: return f'{self.name}遛{self.dog.breed}品种的{self.dog.name}' class Dog: def __init__(self, name: str, gender: str, breed: str): self.name = name self.gender = gender self.breed = breed def call_out(self): return f'{self.name}叫唤' dog1 = Dog('阿黄', '雌', '疯狗') person1 = Human('黄哥', 18, dog1) print(dog1.call_out(), person1.walk_the_dog())
``