In this course, I was requested to expand “explore” method and I did as I was told but I couldn’t manage to understand how I could manage to call “explore” method on “excavation_site”.
Here in this code I called explore method on “excavation_site” and it worked but “excavation_site” is an instance of “build_graph” function and this function has no “explore” method or attribute. Actually, Graph has “explore” method or attribute. How did “explore” method worked with “excavation_site”?
build_graph() is invoked, it returns an instance of
Graph class. This is stored in excavation_site. That’s how excavation_site is an instance of
Graph class. If you want to verify you can probably type something like
Hope this helps!
Thank you so much. So, we can say it becomes an instance of graph class automatically. Right ?
What is the logic behind this, why does excavation_site becomes an instance of Graph ?
Consider what the
build_graph() function does. Inside it, an instance of
Graph is first instantiated without any specific properties. Then, still inside, properties are added specifically for our “maze graph”. A more accurate name for the function could be
build_maze_graph() as it is a function that only makes sense within the context of this program. If you wanted to make a graph with diff specs, you couldn’t use this function.
excavation_site is simply passed the return value of the
build_graph() function. If you just invoke
build_graph(), the created graph won’t be stored anywhere.
I got it already but, shouldn’t it be like “excavation_site.graph.explore()”? Because “excavation_site” instantinate or is equal to “build_graph” function but “build_graph” function have not explore() method but “graph” variable which is in “build_graph” function, has explore() method as it is instance of “Graph()” class. So, now wasn’t “excavation_site.graph.exlore()” more accurate and shouldn’t “excavation_site.explore()” be working as explore() method do not belong to “build_graph” function ?
I hope I could describe my question correctly.
So it’s a bit complicated to think of the
= operator as equals in programming.
When one writes
excavation_site = build_graph() it doesn’t means excavation_site is equivalent to
build_graph() function. It’s more accurate to say, let the value of
excavation_site be whatever the value of
build_graph() resolves to. And since the value it resolves to is an instantiation of a new Graph class,
excavation_site is now a new Graph class.
excavation_site.graph.explore() wouldn’t work because
excavation_site is the graph. That’s like saying
Try putting a bunch of print statements with the
type() method to highlight what each thing is.
For example, in the terminal, look at this interaction:
>>> def number(): ... return 5 ... >>> type(number) <class 'function'> >>> type(number()) <class 'int'>
type(build_graph) would return a value of
<class 'function'>, but
type(build_graph()) would return a value of
<class '__main__.Graph'> or something to that extent.