1. 如下代码,使用图文分析整个内存过程
class Student:
company = "尚学堂" # 类属性
def __init__(self, name, score):
self.name = name # 实例属性
self.score = score
Student.count += 1
def say_score(self):
print("我的公司是:", Student.company )
print(self.name , '的分数是:', self.score )
# 创建实例对象s1,自动调用__init__()方法
s1 = Student('高淇', 80)
# 调用实例方法say_score()
s1.say _score()
print('一共创建{0}个 Student 对象'.format(Student.count ))
2. 设计一个名为 MyRectangle 的矩形类来表示矩形。这个类包含:
(1) 左上角顶点的坐标:x,y
(2) 宽度和高度:width、height
(3) 构造方法:传入 x,
y,width,height。如果(x,y)不传则默认是 0,如果 width
和 height 不传,则默认是 100.
(4) 定义一个 getArea() 计算面积的方法
(5) 定义一个 getPerimeter(),计算周长的方法
(6) 定义一个 draw()方法,使用海龟绘图绘制出这个矩形
import turtle class MyRectangle: def __init__(self, x=0, y=0, width=100, height=100): self.x = x self.y = y self.width = width self.height = height def getArea(self): Area=self.width * self.height return Area def getPerimeter(self): return 2 * (self.width + self.height) def draw(self): turtle.penup() turtle.goto(self.x, self.y) turtle.pendown() turtle.goto(self.width,self.y) turtle.goto(self.width,self.height) turtle.goto(self.x,self.height) turtle.goto(self.x,self.y) turtle.done() rect = MyRectangle() print(f"矩形面积:{rect.getArea()}") print(f"矩形周长:{rect.getPerimeter()}") rect.draw()