文章目录
-
-
-
- 面向对象练习
- Python基础回顾
-
- 常见 python 面试题目整理
-
- 1. 列举 Python2 和 Python3 的区别?
- 2. 简述 Python 的深浅拷贝以及应用场景?
- 3. 能否解释一下 *args 和 **kwargs?
- 4. 简述 生成器、迭代器、可迭代对象 以及应用场景?
- 5. 请说明 yield 关键字的工作机制。
- 6. 请简单谈谈装饰器的作用和功能。
- 7. Python 中如何读取大数据的文件内容?
- 8. Python 中的模块和包是什么?
- 9. python 是如何进行内存管理的(python 是如何实现垃圾回收机制的)?
- 10. 谈谈你对面向对象的理解?
- 11. Python 面向对象中的继承有什么特点?
- 12. 面向对象中 super 的作用?
- 13. 面向对象深度优先和广度优先是什么, 并说明应用场景?
- 14. 请简述__init__和__len__这两个魔术方法的作用
-
-
面向对象练习
question1. 队列数据结构的封装
队列类。队列(queue)是具有先进先出(FIFO)特性的数据结构。一个队
列就像是一行队伍,数据从前端被移除,从后端被加入。这个类必须支持
下面几种方法:
并实现下面的功能:
代码如下:
class Queue(object):
"""
根据列表的数据结构封装栈的数据结构
"""
# 构造方法
def __init__(self):
# 定义一个空队列, 用来存储队列的元素
self.__queue = []
# len(queueobj)自动会调用该方法
def __len__(self):
return len(self.__queue)
def push(self, item):
"""入队列"""
self.__queue.append(item)
print("元素[%s]加入队列成功" % (item))
def pop(self):
"""出队列, 判断队列是否为空"""
if not self.is_empty():
# 获取出栈的元素
item = self.__queue.pop(0)
print("元素[%s]弹出队列成功" % (item))
else:
raise Exception("队列为空")
def top(self):
"""获取队列顶元素"""
if not self.is_empty():
# 获取出栈的元素
item = self.__queue[0]
print("队列顶元素为: [%s] " % (item))
else:
raise Exception("队列为空")
def length(self):
"""获取栈的元素个数"""
return len(self.__queue)
def is_empty(self):
"""判断栈是否为空"""
return len(self.__queue) == 0
queue = Queue()
queue.push(5)
print(len(queue))
queue.push(3)
queue.pop()
print(queue.is_empty())
queue.pop()
print(queue.is_empty())
print(len(queue))
结果如下: