I’ve been working through the Python 2 book and, when I was approaching the end, I came across Exercise 43, “Gothons from Planet Percal #25”. I realized that I couldn’t for the life of me understand the Engine class that was a part of the code. It used a function that contained two periods, and I didn’t really have any idea what that meant. I’ve been looking all over the book for a direct explanation of the period operator because now I’m doubting my understanding of it completely. I’m not even sure whether it really is an operator or just agreed upon notation. I’m really confused, and on top of that, none of the other stuff in the Engine class makes any sense to me either, but I might just save that for another post.
This is a very tricky part to understand. It took me a long time before I understood what was happening.
At the bottom you have
a_map = Map('hall') a_game = Engine(a_map) a_game.play()
a_map instanstiates the Map class with ‘hall’ as a parameter.
Then a_game instanstiates the Engine class with a_map as a parameter.
That gives the Engine class access to the methods in the Map class.
If you look at:
current_scene = self.scene_map.opening_scene()
“current_scene” is a variable that will get a value from:
def __init__(self, scene_map)
in the Engine class.
from Map class.
Because Map got ‘hall’ as parameter, now current _scene has the value ‘hall’ through the self.scene_map.opening_scene methods.
The ‘self’ is also neccesary when one use a parameter from another method.
I have unfortunately no deeper understanding in how self works.
Yes, @ulfen69 has the right answer. There is also a series of videos I published which helps people understand OOP more:
The main thing is, you have to remember that if you can do something in one place, you can usually do it again or in another place. If I have this code:
x = y.bar x.doit()
Then I can combine those two lines with:
If doit then returned another object with a method I could continue:
That’s the same as if you did this:
j = y.bar.doit() j.anotherthing()
I don’t have to do everything in one step on one line. As long as I can keep chaining together objects and their attributes I can keep using the . on each returned object. Another key point is, when you call a function it returns something. And, you don’t have to save that something in a variable. You can just use it right away, and python will keep it temporarily as it continues the calculation.
Thank you guys so much!