Skip to content

Commit 16f9cf4

Browse files
committed
Python解释器理解
1 parent 569bd19 commit 16f9cf4

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,42 @@ class HashTable(object):
409409
```
410410

411411

412+
### interpreter.py Python解释器理解
413+
```
414+
Python会执行其他3个步骤:词法分析,语法解析和编译。
415+
这三步合起来把源代码转换成code object,它包含着解释器可以理解的指令。而解释器的工作就是解释code object中的指令。
416+
核心代码
417+
class Interpreter:
418+
def __init__(self):
419+
self.stack = []
420+
421+
def load_value(self, number):
422+
self.stack.append(number)
423+
424+
def print_answer(self):
425+
answer = self.stack.pop()
426+
print(answer)
427+
428+
def add_two_values(self):
429+
first_num = self.stack.pop()
430+
second_num = self.stack.pop()
431+
total = first_num + second_num
432+
self.stack.append(total)
433+
434+
def run_code(self, what_to_execute):
435+
instructions = what_to_execute["instructions"]
436+
numbers = what_to_execute["numbers"]
437+
for each_step in instructions:
438+
instruction, argument = each_step
439+
if instruction == "load_value":
440+
number = numbers[argument]
441+
self.load_value(number)
442+
elif instruction == "add_two_values":
443+
self.add_two_values()
444+
elif instruction == "print_answer":
445+
self.print_answer()
446+
```
447+
412448

413449

414450

interpreter.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author: lock
3+
# @Date: 2017-12-18 15:21:43
4+
# @Last Modified by: lock
5+
# @Last Modified time: 2017-12-18 15:40:25
6+
7+
class Interpreter:
8+
def __init__(self):
9+
self.stack = []
10+
11+
def load_value(self, number):
12+
self.stack.append(number)
13+
14+
def print_answer(self):
15+
answer = self.stack.pop()
16+
print(answer)
17+
18+
def add_two_values(self):
19+
first_num = self.stack.pop()
20+
second_num = self.stack.pop()
21+
total = first_num + second_num
22+
self.stack.append(total)
23+
24+
def run_code(self, what_to_execute):
25+
instructions = what_to_execute["instructions"]
26+
numbers = what_to_execute["numbers"]
27+
for each_step in instructions:
28+
instruction, argument = each_step
29+
if instruction == "load_value":
30+
number = numbers[argument]
31+
self.load_value(number)
32+
elif instruction == "add_two_values":
33+
self.add_two_values()
34+
elif instruction == "print_answer":
35+
self.print_answer()
36+
37+
interpreter = Interpreter()
38+
what_to_execute = {
39+
"instructions": [("load_value", 0),
40+
("load_value", 1),
41+
("add_two_values", None),
42+
("print_answer", None)],
43+
"numbers": [7, 5] }
44+
interpreter.run_code(what_to_execute)

0 commit comments

Comments
 (0)