6 Replies - 2113 Views - Last Post: 30 July 2013 - 09:04 AM Rate Topic: -----

#1 guren  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 25-March 13

Trouble understanding Python classes

Posted 11 July 2013 - 06:38 PM

Hey guys, I have been trying to wrap my head around this piece of code:

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()

        while True:
            print "\n--------"
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laser_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death()

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        return Map.scenes.get(scene_name)

    def opening_scene(self):
        return self.next_scene(self.start_scene)

a_map = Map('central_corridor')
a_game = Engine(a_map)

class Scene(object):

    def enter(self):
        print "This scene is not yet configured. Subclass it and implement enter()."

The full code is in this link --> http://learnpythonth.../book/ex43.html

I was doing great until I stumble across this exercise, I have done alot of extra research online about Python classes, the __init___ method, and self parameter, but most of the time I end up with more questions than answers. Also I've been creating my own classes to test them and see how they work, sience in the past creating my own code so I can add and removes things at will has really helped me to understand how the code gets executed step by step but classes have been a real challenge.

My problems:

1-I need help understanding how __init__ and self work.

2-I having difficulty understanding what happens, for lack of a better word, to the arguments you pass to a class, examples Map('central_corridor'), Engine(a_map).

3-I am having trouble undestanding the Engine and Map classes.

Any help with problems 1, 2 or 3 is greatly appreciated.

A big thank you in advance.

I will continue trying to figure it out!!!

The roots of education are bitter but the fruit is sweet!!!

Is This A Good Question/Topic? 0
  • +

Replies To: Trouble understanding Python classes

#2 ConciselyVerbose  Icon User is offline

  • D.I.C Regular

Reputation: 91
  • View blog
  • Posts: 315
  • Joined: 05-July 13

Re: Trouble understanding Python classes

Posted 11 July 2013 - 07:45 PM

1 init is called when you create an object of the class. When Map('central_corridor') is called, it calls the init method.

def __init__(self, start_scene):
     self.start_scene = start_scene

Self is the object you created. start_scene is the 'central_corridor' passed in. self.start_scene is the variable that is stored to the class.

Self is not an official keyword, but when you call a method of a class on an object, the first parameter is that object you call it on (a_game.play() is the same as Engine.play(a_game)), and using self to refer to it is a common convention.

As for what it does, I'll leave that to you. The only way to really figure it out is to dive in and try it.

This post has been edited by ConciselyVerbose: 11 July 2013 - 09:53 PM

Was This Post Helpful? 1
  • +
  • -

#3 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 165
  • View blog
  • Posts: 258
  • Joined: 19-July 09

Re: Trouble understanding Python classes

Posted 11 July 2013 - 08:15 PM

Think of a class as a blueprint to create some object (an so called instance of the class). Just like built ins like list. __init__ is called when an instance is created and self refers to the instance.

Two toy examples that I hope help (not sure its late here and I am bad at explaining things late at night):
one = [1,1,1]
two = [2,2,2]
#one and two are instances of the list "class"
#(1,1,1) and (2,2,2) are passed to the __init__ of the list class

#"self" is explicitly used
list.append(one, 1)
print one
#the above is the same as
#self is implicitly used
print two

#class definition
class MySilly(object):
    def __init__(self, initial_values_of_instances):
        self.im_who = initial_values_of_instances
    def who_am_I(self):
        return self.im_who

#up to here python knows that there is a class
#but has not done anything with it (except creating a namespace for it)

#create some instances:
one = MySilly("1")
two = MySilly("2")

#do something with them
print "calling one"
print one.who_am_I()
print "calling two"
#for a twist use the instance explicitly
#call it via the class
#but this time we need to pass in the instance
#in the above case it was implicitly given, here we need to do it explicitly:
print MySilly.who_am_I(two)

Was This Post Helpful? 1
  • +
  • -

#4 DblAAssassin  Icon User is offline

  • D.I.C Regular

Reputation: 43
  • View blog
  • Posts: 322
  • Joined: 11-May 13

Re: Trouble understanding Python classes

Posted 16 July 2013 - 04:32 PM

1.The reason why we have __init__ Is called when an instance is created. .self is called so that, when you call that variable, the class, will know what you are talking about. Think of it as a Class Translator.

2. What it is doing there is... in the first one a_map("central corridor"). That is the name of the map for lack of better words of the location. The a_game is calling the a_map, to be used, in the Engine Class.

3. Could you be more specific.

Classes aren't my strong suit, but I'm pretty confident in ^these^ answers.
Was This Post Helpful? 1
  • +
  • -

#5 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon

Reputation: 11040
  • View blog
  • Posts: 18,852
  • Joined: 19-March 11

Re: Trouble understanding Python classes

Posted 16 July 2013 - 07:47 PM

1. As Nallo says, __init__ is called when you create a new instance. For example, the built-in list class has an __init__ method that sets up the class. That method is called when you use
>>> list()  # return an empty list

to return an instance of list.

So if you make a class called Dog, you'll define an __init__, and then to create a new Dog object you'll use

>>> Dog() # return some generic mutt, I suppose

self is a reference to the instance. Python's handling of this parameter is a little idiosyncratic, but under the hood, other languages do something very similar: pass a reference to the object you're working on, so it knows where it is, and how to modify itself. In Java, for example, that reference is called this, and while it's not mentioned in any method declarations, it's actually passed on the stack just as self

Self is really just a pointer: when you call a method on an object, that object will probably make use of some of its stored variables ("state"). Self tells the machine which instance's state to make use of.

2. A method's parameters are essentially a set of local variable declarations, whose values are supplied from outside the local context.

def add_7(x):
  seven = 7
  x =  x + seven
  return x

There are two local variables here: x and seven. seven is initialized inside the body of the function, x is provided by the calling process.

>>> add_7(13)

Both x and seven are local to the function: their values do not affect any other variables outside of add_7() nor are they affected by them, even if those variables have the same name.

>>> x = 14
>>> seven = 45

>>> add_7(13)

So what happens to the arguments to a function? They are assigned to the function's parameters according to certain known rules. These rules can be complicated, since python allows you some flexibility in your variables, but the values in the arguments list are used bby the function.

What happens to them afterward? Nothing! The function uses those values to do its work, but it's working on local variables.

>>> x = 14

>>> add_7(x)

>>> x

x does not change here, even though we've passed it into this function!

(and, though this probably didn't strike you as odd, neither did the value of 13 when you used that as the argument...)

One warning, though: there's a gotcha that you have to be aware of!

We talk about "passing an object to a function". When we do this, we pass a reference to that object. What you do to that reference doesn't affect the original reference that you copied it from, but if you call a method on the object that method refers to, that method will affect that object. This is sometimes called "aliasing", since you've got one object trading under two different names.

A few quick examples to get you started understanding this, but you should do your own experiments and research to understandd it thoroughly.

>>> a_list = [1,2,3,4]
>>> b_list = a_list
>>> b_list.reverse()
>>> a_list
[4, 3, 2, 1]
>>> a_list.pop(0)
>>> b_list
[3, 2, 1]

This is all standard stuff - you can probably see what's going on. b_list is not a copy of a_list, it's another name for a_list. So what you do to one, you do to the other.

Now I said before that the arguments to a function are assigned to the function's parameters. What do you think happens here?
def reverse_and_pop(some_list):
a_list = [1,2,3,4]

Make sure you understand why!

This post has been edited by jon.kiparsky: 17 July 2013 - 05:20 AM

Was This Post Helpful? 3
  • +
  • -

#6 guren  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 25-March 13

Re: Trouble understanding Python classes

Posted 17 July 2013 - 10:41 AM

Hey guys I want to thank you all for your help, I have to say that thanks to you guys I'm understanding alot better the python programming language. A special thanks to Nallo and jon.kiparsky your examples are great.

Also for anyone trying to understand python classes, or python in general, I really recommend this book--> http://www.greenteap...html/index.html , it is called Think Python and it has really helped me on the python class subject. You can read it online for free. Also MIT Introduction to Computer Science and Programming from OpenCourseWare recommends it as an alternative if you can't buy the class book.
Was This Post Helpful? 1
  • +
  • -

#7 hanabijm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 30-July 13

Re: Trouble understanding Python classes

Posted 30 July 2013 - 09:04 AM

Another way to think of __init__ : It is called when a new object is requested by your program. It uses arguments to assign attributes on the new object that was just requested
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1