1. Python中的基本数据类型有哪些?
# Python基本数据类型示例
a_int = 10 # 整数 int
b_float = 3.14 # 浮点 float
c_bool = True # 布尔 bool
d_str = "hello" # 字符串 str
e_list = [1, 2, 3] # 列表 list
f_tuple = (4, 5) # 元组 tuple
g_dict = {"k": 1} # 字典 dict
h_set = {1, 2, 3} # 集合 set
2. Python的装箱和拆箱?
Python中不存在严格意义上的装箱拆箱,因为所有变量本质上都是对象引用。但有自动类型转换:
x = 10 # 整数对象
y = float(x) # 显式转换为浮点数,类似装箱过程
3. Python中==和is的区别?
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == c) # True,比较内容是否相等
print(a is c) # False,比较是否是同一对象
print(a is b) # True,b引用a同一个对象
4. Python中的常量池?
Python中小整数和字符串有内部缓存机制(类似常量池):
a = 256
b = 256
print(a is b) # True,引用同一个小整数对象
s1 = "hello"
s2 = "hello"
print(s1 is s2) # True,字符串常量缓存
5. Python中字符串和列表的区别?
s = "abc"
# 字符串不可变
try:
s[0] = "z"
except TypeError:
print("字符串不可变")
lst = ['a', 'b', 'c']
lst[0] = 'z' # 列表可变
print(lst) # ['z', 'b', 'c']
6. Python中的final?
Python没有final关键字,但可用命名约定或第三方库实现常量。
7. Python中接口和抽象类?
Python通过抽象基类(abc模块)实现抽象类:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof"
d = Dog()
print(d.sound()) # Woof
8. Python的内存模型?
Python使用引用计数和垃圾回收(GC)管理内存,线程间通过GIL限制并发。
9. Python中的异常?
try:
1 / 0
except ZeroDivisionError as e:
print(f"异常捕获: {e}")
10. Python中的对象创建?
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice") # 调用__init__构造对象
print(p.name)
11. 多态示例
class Animal:
def speak(self):
pass
class Cat(Animal):
def speak(self):
return "Meow"
class Dog(Animal):
def speak(self):
return "Woof"
def animal_speak(animal: Animal):
print(animal.speak())
animal_speak(Cat())
animal_speak(Dog())
12. 重载和重写?
Python不支持重载(通过默认参数或*args实现),支持重写:
class Base:
def method(self):
print("Base")
class Child(Base):
def method(self):
print("Child")
c = Child()
c.method() # Child
13. 设计模式示例(单例)
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
14. 单例模式(懒加载)示例
class LazySingleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
15. 开闭原则
Python通过继承和多态支持开闭原则,例如在新类中扩展功能而不修改原有代码。
16. Python的列表和链表
Python列表是动态数组,链表可自定义:
class Node:
def __init__(self, val):
self.val = val
self.next = None
# 链表操作示例略
17. Python字典原理?
Python字典基于哈希表实现,key通过hash函数定位存储位置。
18. 哈希冲突解决?
Python哈希表用开放寻址法解决冲突。
19. Python中的线程安全?
内置数据结构大多线程不安全,需用锁(threading.Lock)保护。
20. fail-fast机制?
Python迭代时修改列表不抛异常,但行为未定义,建议避免。
21. Python中如何创建线程?
import threading
def worker():
print("线程运行")
t = threading.Thread(target=worker)
t.start()
t.join()
22. 什么是线程安全?
多个线程访问共享数据时,确保数据一致且无竞态条件。
23. synchronized关键字作用对应Python?
Python用锁threading.Lock
实现同步:
lock = threading.Lock()
def critical_section():
with lock:
# 线程安全代码
pass
24. volatile关键字对应Python?
Python没有volatile,但GIL保证单个字节码操作原子性。多线程共享变量需用锁保证内存可见性。
25. wait()和sleep()区别?
import threading
import time
condition = threading.Condition()
def wait_thread():
with condition:
print("等待中")
condition.wait() # 释放锁并等待通知
print("继续执行")
def sleep_thread():
print("睡眠中")
time.sleep(2)
print("睡眠结束")
26. 什么是死锁?如何避免?
死锁是多个线程互相等待对方释放资源导致互相阻塞。避免方法:避免嵌套锁、统一锁顺序、设置超时。
27. 什么是线程池?Python如何创建?
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(10):
executor.submit(print, f"任务{i}")
28. Callable和Runnable区别?
Python的threading.Thread
可传函数,支持返回值要用concurrent.futures
的Future
对象。
29. 什么是线程中断?
Python线程不能强制中断,需通过变量让线程自行退出。
import threading
import time
stop_flag = False
def run():
while not stop_flag:
print("运行中")
time.sleep(1)
t = threading.Thread(target=run)
t.start()
time.sleep(3)
stop_flag = True
t.join()
30. Java内存模型中happens-before规则对应?
Python内存模型无严格happens-before,但锁和线程同步确保内存可见。
31. JVM内存结构对应Python?
Python内存管理由引用计数和GC负责,栈和堆的概念也适用。
32. 垃圾回收器有哪些?
Python主要用引用计数和分代垃圾回收。
33. 堆内存和栈内存?
Python函数调用使用栈,变量引用指向堆上的对象。
34. JVM类加载过程对应Python?
Python通过import动态加载模块。
35. 类加载器对应?
Python模块查找通过sys.path机制完成。
36. 内存溢出?
Python出现内存溢出通常是无限创建对象或循环引用导致。
37. 软引用、弱引用、虚引用?
Python有weakref
模块实现弱引用:
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r()) # 有对象返回对象
del obj
print(r()) # None,引用失效
38. 如何定位内存泄漏?
用objgraph
、tracemalloc
等工具分析对象引用。
39. 如何避免频繁GC?
减少不必要对象创建,及时释放引用。
40. JVM参数调优对应Python?
Python解释器参数有限,主要优化靠代码和环境。
41. 什么是记录类(record)?
Python的dataclasses
模块类似Java的record,用于简化数据类定义:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(p) # Point(x=1, y=2)
42. 密封类(sealed class)对应?
Python没有密封类,但可以用__init_subclass__
限制继承:
class Sealed:
allowed_subclasses = set()
def __init_subclass__(cls):
if cls.__name__ not in Sealed.allowed_subclasses:
raise TypeError(f"{cls.__name__} 不能继承 Sealed")
class Allowed(Sealed):
pass
Sealed.allowed_subclasses.add("Allowed") # 允许继承
43. 模式匹配(Pattern Matching)
Python 3.10+支持结构化模式匹配:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case _:
return "Other error"
print(http_error(404))
44. switch表达式新特性?
Python没有switch,使用字典映射模拟:
def switch_case(value):
return {
1: "one",
2: "two",
}.get(value, "other")
print(switch_case(1))
45. 文本块(Text Block)
Python支持多行字符串:
text = """
这是
多行文本
"""
print(text)
46. JEP 409密封接口优势
Python通过抽象基类和限制继承达到类似效果,提升安全。
47. Java 17新增垃圾回收器?
Python默认垃圾回收,第三方库可用替代。
48. 用var声明局部变量?
Python变量类型自动推断,无需声明。
49. Foreign Function & Memory API?
Python可用ctypes
或cffi
调用本地C代码。
from ctypes import CDLL
libc = CDLL("libc.so.6")
print(libc.printf(b"Hello %s\n", b"world"))
50. 增强型switch匹配哪些类型?
Python的match可匹配数字、字符串、类实例等。
51. Socket通信原理?
Python Socket示例:
import socket
s = socket.socket()
s.bind(('localhost', 12345))
s.listen()
conn, addr = s.accept()
data = conn.recv(1024)
print(data.decode())
conn.close()
52. BIO、NIO、AIO区别?
Python的socket
默认阻塞,selectors
模块实现非阻塞。
53. 如何实现序列化?
Python用pickle
模块:
import pickle
data = {'a': 1}
s = pickle.dumps(data)
obj = pickle.loads(s)
print(obj)
54. 反序列化漏洞及防范?
避免反序列化不可信数据,使用安全库。
55. 文件IO和NIO区别?
Python普通文件IO和asyncio
实现异步IO。
56. 什么是通道(Channel)?
Python用asyncio.StreamReader/Writer
类似通道。
57. 网络超时?
import socket
s = socket.socket()
s.settimeout(5)
try:
s.connect(('example.com', 80))
except socket.timeout:
print("连接超时")
58. HTTP持久连接?
Python的requests支持持久连接。
59. 处理大文件?
分块读取:
with open("largefile.txt", "r") as f:
for line in f:
process(line)
60. Socket编程常见异常?
socket.timeout
, ConnectionRefusedError
等。