Python: Dictionaries, classes and "switch"

Source: Internet
Author: User

There is no switch syntax in Python, and I want to use a switch-like feature in my practice, and search for the relevant content knowing that using a dictionary can do the steps I want. So, start.

I'm using Python3, and I'm practicing using the Tkinter module to write a little game: Table tennis. In the test phase, I first typed:

 from Import *

This loads the Tkinter module and uses * to make a little bit of code in the subsequent code input. After that, I conceived to create a canvas class variable and draw a rectangle above it to simulate the racket by controlling the rectangle movement by the left and right arrow keys. The complete code for the test is:

1  fromTkinterImport*2 3 4 defmove2right (dis):5Canvas.move (1, dis, 0)6 7 8 defmove2left (dis):9Canvas.move (1,-dis, 0)Ten  OneMovement = {' Right': Move2right,' Left': Move2left} A  -  - defMove (event): theMovement.get (Event.keysym) (8) -  -TK =Tk () -Canvas = Canvas (tk, width=500, height=500) + Canvas.pack () -Canvas.create_rectangle (100, 100, 200, 120) +Canvas.bind_all ('<KeyPress-Right>', move) ACanvas.bind_all ('<KeyPress-Left>', move) at  -Tk.mainloop ()

The results of the above test code are smooth: Use the dictionary variable movement to store pointers to two functions in a dictionary. The 21,22 line binds the left and right trigger events to the function move (), because the function passed in the Bind_all () method has a parameter (event), which is set to an event class inside the Bind_all () method to store the triggered event content, because of the above reasons, I defined the move () function to encapsulate the Movement.get () method. 15 line, the. Get () method can be indexed key to get the corresponding value,event.keysym for Bind_all () the element in the event class passed to the move () function, which is a string representing the corresponding keyboard key (valid here is ' right ' and ' Left '). The last (8) of the 15 line is the parameter of the function.

After the test was successful, I moved this method to the Test table tennis and Racquet bounce file, which has the ball class of table tennis and racket paddle class. Paste the last code that can be run:

1 #!/usr/bin/env Python32 #-*-coding=utf-8-*-3 4  fromTkinterImport*5 Import Time6 7 8 classBall :9     def __init__(self, canvas, color, paddle):TenSelf.canvas =Canvas OneSelf.canvas_height =self.canvas.winfo_height () ASelf.canvas_width =self.canvas.winfo_width () -Self.paddle =Paddle -Self.id = Canvas.create_oval (ten, ten, +, fill=color) theSelf.canvas.move (self.id, 245, 100) -Self.hit_bottom =False -Self.x_pixel_of_one_step = 0#ball Transverse Velocity -Self.y_pixel_of_one_step =-3#Ball longitudinal Velocity +  -     defHit_paddle (Self, POS): +Paddle_pos =self.canvas.coords (self.paddle.id) A         ifPaddle_pos[0] <= (pos[0] + pos[2])/2.0 <= paddle_pos[2]: at             ifPADDLE_POS[1] <= pos[3] < paddle_pos[3] andSelf.y_pixel_of_one_step >0: -                 returnTrue -             ifPADDLE_POS[1] < pos[1] <= Paddle_pos[3] andSelf.y_pixel_of_one_step <0: -                 returnTrue -         returnFalse -  in     defDraw (self): -Ball_pos = Self.canvas.coords (self.id)#extracting the position of the current ball to         #collision to up/down edge bounce parameter setting +         ifBall_pos[1] <= 0orBALL_POS[3] >=Self.canvas_height: -Self.y_pixel_of_one_step =-Self.y_pixel_of_one_step the         #collision to left and right side bounce parameter settings *         ifBall_pos[0] <= 0orBALL_POS[3] >=Self.canvas_width: $Self.x_pixel_of_one_step =-Self.x_pixel_of_one_stepPanax Notoginseng         #collision to Racquet bounce parameter setting -         ifSelf.hit_paddle (ball_pos): theSelf.y_pixel_of_one_step =-Self.y_pixel_of_one_step +         #moving the ball A Self.canvas.move (self.id, Self.x_pixel_of_one_step, Self.y_pixel_of_one_step) the  +  - classPaddle: $     def __init__(self, canvas, color): $Self.canvas =Canvas -Self.canvas_height =canvas.winfo_height () -Self.canvas_width =canvas.winfo_width () theself.id = canvas.create_rectangle (0, 0, ten, fill=color) -Self.canvas.move (Self.id, 250, 250)WuyiSelf.canvas.bind_all ('<KeyPress-Right>', Self.move) theSelf.canvas.bind_all ('<KeyPress-Left>', Self.move) -Self.x_pixel_of_one_step =0 WuSelf.y_pixel_of_one_step =0 -  About     defMove2left (self): $Paddle_pos =self.canvas.coords (self.id) -         ifPaddle_pos[0] >=0: -Self.canvas.move (Self.id, 5, 0) -  A     defmove2right (self): +Paddle_pos =self.canvas.coords (self.id) the         ifPADDLE_POS[2] <=Self.canvas_width: -Self.canvas.move (Self.id, 5, 0) $  theMovement = {' Right': Move2right,' Left': Move2left} the  the     defMove (self, event): the Self.movement.get (Event.keysym) (self) -         #print (Self.movement[event.keysym]) in  the     defDraw (self): the         Pass About  the  theTK =Tk () theTk.title ('Fuck the Ping-pang') +Tk.resizable (0, 0)#limit canvas to not scale -Tk.wm_attributes ('-topmost', 1) theCanvas = Canvas (tk,width=500, height=500, Bd=0, highlightthickness=0)Bayi #canvas = Canvas (tk, width=500, height=500) the Canvas.pack () the tk.update () -Paddle = Paddle (canvas,'Black') -Ball = Ball (canvas,'Black', paddle) the  the  whileTrue: the Ball.draw () the tk.update_idletasks () - tk.update () theTime.sleep (0.01)

Everything is OK except 56~70. These lines are just the way I've joined the method shown. the place where I'm tangled is on line 69th . I'm baffled by the contents of this line.

For the definition of a class method, the first parameter of all class methods must be a self (variable name) parameter, which defaults to the class in which the method is said, making it easy to write related content within the method. When using a method, the self parameter is hidden, meaning that the parameter is not visible externally. For example, the Move2left () function (56 rows) in the paddle class, when using the Move2left () function in a class method definition, only needs to write Self.move2left (), and the internal self parameter does not need to be written. But on line 69, I have to add self to the argument. Revisit 69 lines:

Self.movement.get (Event.keysym) (self)

The self parameter here is the default parameter, self, in the Move () method, which points to the paddle class, which is a function pointer. Why write this parameter in the display?

Two contents are saved in dictionary movement, which are pointers to move2left functions and Move2right functions, respectively. Then, when using Movement.get (' right '), it is equivalent to returning move2right. Well, movement.get (' right ') () This code is equivalent to the call of Move2right (), and the final parenthesis indicates that the preceding content is a function, and that running without it is definitely not possible (it cannot be compiled, because Python is an explanatory language). For a function of a non-class method , there are no parameters to set the default value in the parameter of the function definition, when calling this function, the argument must be passed in at the corresponding parameter position, and the Python interpreter will not run the function correctly to make an error if not enough arguments are passed. For a function in a class method , because the Python interpreter "treats" the class differently, the interpreter automatically "crosses" the first variable in the class method to a pointer to its own class when the class method is called.

But the tangled place came. When using the Dictionary method get (), the Get method simply returns the value of Ching (key) in the dictionary. The address of the Move2left or Move2right function is returned here. When the interpreter runs here and comes out of the Get () method, a function pointer is obtained. At this point, however, the interpreter does not know if the pointer is a method in a class, it only knows that the function pointer is pointing to a function that requires a parameter self, so when combined with the following parentheses () and interpreted as a function, it needs the corresponding number of arguments, so at this time the input of the self parameter cannot be ignored.

Again, the problem is that Python is a hidden data type. And in this case, the self parameter of both Move2left and move2right is not used, so can I pass in another parameter without passing in self, for example: Self.movement.get (Event.keysym) (20). While this is meaningless, it does not conflict with the behavior of the previous Python interpreter. Well, the result is no suspense: error running. Run error, then there is basically only one reason: when the interpreter combines the get () method with the following parentheses and interprets it as a function, the interpreter interprets the function as a non-class method, which is used as a normal function to detect whether the number of arguments passed is consistent with the number of definitions. After the detection parameters are consistent, the program will enter this function by a function pointer, and then find that this function is a class Method! Then it examines the arguments passed to the function again, when the arguments passed to the function have a--20, and the parameters of the class method are defined by a default self. The interpreter accepts this fact and assigns the value of 20 to self. Because the script is running, the program continues to run (for example, by pressing the left button, the Move2left () method is skipped). The Self.canvas.move () method is used in the Move2left method, and the interpreter finds that self equals 20! It's not a class! All right, all right, let's get this error.

Closed.

Python: Dictionaries, classes and "switch"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.