定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
class Dog:
def __init__(self, name, gender, breed):
self.name = name
self.gender = gender
self.breed = breed
def get_bark(self):
return '汪汪汪'
d1 = Dog('黑虎', '男', '中华田园犬')
print(d1.name, d1.get_bark())
黑虎 汪汪汪
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Person:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
return '自在惬意'
p1 = Person('Ziv', '20', '黑虎')
print(p1.name, p1.walk_dog())
Ziv 自在惬意
class Ractangle:
def __init__(self, lenth, width):
self.lenth = lenth
self.width = width
def get_area(self):
return self.lenth * self.width
def get_perimeter(self):
return 2 * self.lenth * self.width
def __repr__(self):
return print(f'面积为{self.get_area()},周长为{self.get_perimeter()}')
R1 = Ractangle(8, 4)
print(R1.get_area(), R1.get_perimeter())
32 64
class Coordinate_axis:
def __init__(self, x, y):
self.x = x
self.y = y
def get_xdistance(self):
return abs(self.x)
def get_ydistance(self):
return abs(self.y)
def __repr__(self):
return print(self.get_xdistance(), self.get_ydistance())
C1 = Coordinate_axis(-4, 5)
print(C1.get_xdistance(), C1.get_ydistance())
4 5
class Circle:
pi = 3.1415926
def __init__(self, radius, center, radius2, center2):
# self.pi = 3.1415926
self.radius = radius
self.center = center
self.radius2 = radius2
self.center2 = center2
def get_area(self):
return Circle.pi * self.radius ** 2, Circle.pi * self.radius2 ** 2
def get_perimeter(self):
return 2 * Circle.pi * self.radius, 2 * Circle.pi * self.radius2
def get_ex_contact(self):
if abs(self.radius) + abs(self.center) == abs(self.radius2) + abs(self.center2):
return print('外切')
else:
return print('不外切')
def __repr__(self):
return f'圆的面积是{self.get_area()},周长是{self.get_perimeter()}', f'圆2的面积是{self.get_area()},周长是{self.get_perimeter()}, 两个圆{self.get_ex_contact()}'
class Line:
def __init__(self, start, end):
self.start = start
self.end = end
def get_sedistance(self):
return abs(self.start) + abs(self.end)
def __repr__(self):
return print(f'两点的距离为{self.get_sedistance()}')
L1 = Line(-9, 8)
print(L1.get_sedistance)
两点的距离为17