# 嵌套状态机

Description: 本教程给出了在另一个状态机中嵌套状态机的示例，并创建了分级状态机。

Tutorial Level: BEGINNER

Next Tutorial: 并行状态

```   1 #!/usr/bin/env python
2
4 import rospy
5 import smach
6 import smach_ros
7
8 # define state Foo
9 class Foo(smach.State):
10     def __init__(self):
11         smach.State.__init__(self, outcomes=['outcome1','outcome2'])
12         self.counter = 0
13
14     def execute(self, userdata):
16         if self.counter < 3:
17             self.counter += 1
18             return 'outcome1'
19         else:
20             return 'outcome2'
21
22
23 # define state Bar
24 class Bar(smach.State):
25     def __init__(self):
26         smach.State.__init__(self, outcomes=['outcome1'])
27
28     def execute(self, userdata):
30         return 'outcome1'
31
32
33
34 # define state Bas
35 class Bas(smach.State):
36     def __init__(self):
37         smach.State.__init__(self, outcomes=['outcome3'])
38
39     def execute(self, userdata):
41         return 'outcome3'
42
43
44
45
46 def main():
47     rospy.init_node('smach_example_state_machine')
48
49     # Create the top level SMACH state machine
50     sm_top = smach.StateMachine(outcomes=['outcome5'])
51
52     # Open the container
53     with sm_top:
54
56                                transitions={'outcome3':'SUB'})
57
58         # Create the sub SMACH state machine
59         sm_sub = smach.StateMachine(outcomes=['outcome4'])
60
61         # Open the container
62         with sm_sub:
63
64             # Add states to the container
66                                    transitions={'outcome1':'BAR',
67                                                 'outcome2':'outcome4'})
69                                    transitions={'outcome1':'FOO'})
70