【Python程序设计】面向对象编程

Alex_Shen
2022-03-31 / 0 评论 / 0 点赞 / 106 阅读 / 6,553 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1. 编写类 RegularPolygon

表示正 n 边形。类包括:

  1. 私有成员 n,要求为整型,代表正 n 边形边的数量,注意n ≥ 3;

  2. 私有成员 side,代表正 n 边形每条边的长度;

  3. 私有成员 x,代表正 n 边形中心的坐标在 x 轴上的数值;

  4. 私有成员 y,代表正 n 边形中心的坐标在 y 轴上的数值;

  5. 构造函数,输入参数为 n(默认为 3),side(默认为 1),x(默认为 0),y(默认为 0);

  6. 方法 getPerimeter,返回正 n 边形的周长;

  7. 方法 getArea,返回正 n 边形的面积;

  8. 方法 distanceToPolygon,输入参数为另外一个正 n 边形,返回两个正 n边形中心的距离。

自行设计测试函数验证 RegularPolygon 类代码的正确性。

import math


class RegularPoylygon:
    def __init__(self, n=3, side=1, x=0, y=0) -> None:
        self.n = n
        self.side = side
        self.x = x
        self.y = y

    def getPerimeter(self):
        print("Perimeter = {:.3f}".format(self.n*self.side))

    def getArea(self):
        print("Area = {:.3f}".format(self.n*self.side *
                                     self.side/math.tan(math.pi/self.n)/4))

    def distanceToPolygon(self, other):
        print("Distance is {:.3f}".format(
            math.sqrt(pow(self.x-other.x, 2) + pow(self.y-other.y, 2))))


square = RegularPoylygon(4, 8, 0, 0)
triangle = RegularPoylygon(3, 3, 1, 1)
square.getArea()
square.getPerimeter()

triangle.getArea()
triangle.getPerimeter()

square.distanceToPolygon(triangle)
triangle.distanceToPolygon(square)

2. 自定义数据结构栈

栈是一种后进先出(Last-In-First-Out)的数据结构。

编写类 Stack,实现入栈、出栈、判断栈是否为空,是否满栈、以及改变栈容量等操作。

Stack 类包括:

  1. 私有成员 content,为一个列表,代表栈里的数据;
  2. 私有成员 size,要求为整型,代表栈的容量;
  3. 私有成员 current,要求为整型,代表栈当前数据的个数;
  4. 方法 isempty,判断栈是否为空,返回 True/False;
  5. 方法 empty,置空栈;
  6. 方法 setSize,输入参数为新的栈的容量。注意新的栈容量可能小于原有的栈容量,统一将后进的元素删除;
  7. 方法 isFull,判断栈是否为空,返回 True/False;
  8. 方法 push,入栈,输入参数为新的元素;
  9. 方法 pop,出栈;
  10. 方法 show,打印当前栈的数据。

自行设计测试函数验证 Stack 类代码的正确性。

class stack:
    def __init__(self, size) -> None:
        self.content = []
        self.size = size
        self.current = 0

    def isempty(self):
        return self.current == 0 and len(self.content) == 0

    def empty(self):
        self.current = 0
        self.content.clear()

    def setSize(self, new_size):
        if new_size < self.size:
            self.content = self.content[:new_size]
            self.current = new_size
        self.size = new_size

    def isFull(self):
        return self.current == self.size

    def push(self, ele):
        if not self.isFull():
            self.content.append(ele)
            self.current += 1
        else:
            print("非法操作")

    def pop(self):
        if not self.isempty():
            self.content.pop()
            self.current -= 1
        else:
            print("非法操作")

    def show(self):
        print(self.content)


myStack = stack(5)
# print(myStack.isempty())
# myStack.pop()
myStack.push(1)
myStack.push(2)
myStack.pop()
myStack.show()
# myStack.push(3)
# myStack.push(4)
# myStack.push(5)
# myStack.show()
# print(myStack.isFull())
# myStack.push(1)
# myStack.show()
# myStack.setSize(3)
# myStack.show()
# print("current =", myStack.current)
# print("size =", myStack.size)
# myStack.setSize(6)
# myStack.show()
# print("current =", myStack.current)
# print("size =", myStack.size)
# myStack.pop()
# myStack.pop()
# myStack.pop()
# myStack.pop()
# print(myStack.isempty())

3. 时间类:

设计一个名为 Time 的类。该类包含:

  1. 表示时间的私有成员 hour、minute 和 second。
  2. 构造 Time 对象的构造函数,使用当前时间 **time.time()**初始化小时、分钟和秒。
  3. hour、minute 和 second 的 get 方法。
  4. 方法 setTime(elapseTime),设置经过了 elapseTime(以秒为单位)后的新时间。
import time as T


class Time:
    def __init__(self) -> None:
        self.__time = T.time()
        time = T.localtime(self.__time)
        self.__hour = time.tm_hour
        self.__minute = time.tm_min
        self.__second = time.tm_sec

    def getHour(self):
        return self.__hour

    def getMinute(self):
        return self.__minute

    def getSecond(self):
        return self.__second

    def setTime(self, elapseTime):
        Time = T.localtime(self.__time+int(elapseTime))
        self.__hour = Time.tm_hour
        self.__minute = Time.tm_min
        self.__second = Time.tm_sec

    def __str__(self) -> str:
        return "时间是:{:02d}:{:02d}:{:02d}".format(self.__hour, self.__minute, self.__second)


myTime = Time()
print("Hour:{:02d}".format(myTime.getHour()))
print("Minute:{:02d}".format(myTime.getMinute()))
print("Second:{:02d}".format(myTime.getSecond()))
print(myTime)
myTime.setTime(20)
print(myTime)

4. 继承 1:

补充代码 lab7_4.py,使得代码输出如下。注:不允许在类中添加新的方法。

if __name__ =='__main__':
	zhangsan = Person('Zhang San', 19, 'man')
	zhangsan.show()
	#Name: Zhang San
	#Age: 19
	#Sex: man

	lisi = Teacher('Li Xi',32, 'man', 'Math')
	lisi.show()
	#Name: Li Xi
	#Age: 32
	#Sex: man
	#Department: Math
	
	lisi.setAge(40)
	lisi.setName("Li Si")
	lisi.show()
	#Name: Li Si
	#Age: 40#Sex: man
	#Department: Math

lab7.4 如下:

# -*- coding:utf-8 -*-

class Person(object):
    def __init__(self, name='', age=20, sex='man'):
        pass

    def setName(self, name):
        pass

    def setAge(self, age):
        pass

    def setSex(self, sex):
        pass

    def show(self):
        pass


class Teacher(Person):
    def __init__(self, name='', age=30, sex='man', department='Computer'):
        Person.__init__(self, name, age, sex)
        self.setDepartment(department)

    def setDepartment(self, department):
        pass

    def show(self):
        pass


if __name__ == '__main__':
    zhangsan = Person('Zhang San', 19, 'man')
    zhangsan.show()

    lisi = Teacher('Li Xi', 32, 'man', 'Math')
    lisi.show()
    lisi.setAge(40)
    lisi.setName("Li Si")
    lisi.show()

答案:

# -*- coding:utf-8 -*-

class Person(object):
    def __init__(self, name='', age=20, sex='man'):
        self.__name = name
        self.__age = age
        self.__sex = sex

    def setName(self, name):
        self.__name = name

    def setAge(self, age):
        self.__age = age

    def setSex(self, sex):
        self.__sex = sex

    def show(self):
        print("Name:", self.__name)
        print("Age:", self.__age)
        print("Sex:", self.__sex)


class Teacher(Person):
    def __init__(self, name='', age=30, sex='man', department='Computer'):
        Person.__init__(self, name, age, sex)
        self.setDepartment(department)

    def setDepartment(self, department):
        self.__department=department

    def show(self):
        Person.show(self)
        print("Department:",self.__department)


if __name__ == '__main__':
    zhangsan = Person('Zhang San', 19, 'man')
    zhangsan.show()

    lisi = Teacher('Li Xi', 32, 'man', 'Math')
    lisi.show()
    lisi.setAge(40)
    lisi.setName("Li Si")
    lisi.show()

5. 继承 2:研究以下代码,思考代码的输出,并解释。

class China:
    def __init__(self, given, family):
        self.given = given
        self.family = family
    def __str__(self):
        return self.given + ' ' + self.family + '\n' + self.get_description()
    def get_description(self):
        return 'From China'
    def execute(self):
        print(self.family)


class Guangdong(China):
    def __init__(self):
        China.__init__(self, 'Ming', 'Li')


class England(China):
    def __init__(self):
        China.__init__(self, 'David', 'Beckham')
    def get_description(self):
        return 'From England'


def test_person(person):
    print(person)


ming = Guangdong()
ming.execute()
test_person(ming)
test_person(England())

答案:

class China:
    def __init__(self, given, family):
        self.given = given
        self.family = family
    def __str__(self):
        return self.given + ' ' + self.family + '\n' + self.get_description()
    def get_description(self):
        return 'From China'
    def execute(self):
        print(self.family)


class Guangdong(China):
    def __init__(self):
        China.__init__(self, 'Ming', 'Li')


class England(China):
    def __init__(self):
        China.__init__(self, 'David', 'Beckham')
    def get_description(self):
        return 'From England'


def test_person(person):
    print(person)


ming = Guangdong()
ming.execute()
test_person(ming)
test_person(England())

0

评论区