A Methodical Approach (Seeking an Explanation)


#1

https://www.codecademy.com/en/courses/learn-python/lessons/introduction-to-classes/exercises/a-methodical-approach

I am still not not sure if I understand the init method. Specifically, I don’t understand how to create the instances. Can we only create instances with the init method? Please view the code below, any explanations regarding what is truly going on would be greatly appreciated.

Thank you,

```python

Replace this line with your code.
def description(self):
print self.name
print self.age

hippo = Animal(“miz”, 7) # this line is very ambiguous to me. Are we creating a copy of the class?

print hippo.description()


#2

This is an instance…

No. We can create an instance of any class, with or without __init__().

class Foo(object):
    pass

bar = Foo()

print isinstance(bar, Foo)    # True

As we see, though, the instance has no member or instance variables.

Say we want a class to define player scores where everyone starts at 0.

class Player(object):
    score = 0

lloyd = Player()
alice = Player()
tyler = Player()

print lloyd.score    # 0
alice.score += 5
print alice.score    # 5
tyler.score += 10
print tyler.score    # 10

#3

Let me add to @mtf explanation.

The instance is meaning that you are creating an object from the class. You can think of a class as a blueprint, which defines how to build that object, what it can do (methods), and what information it can have (data part of it).

Think about a house. We build a house from a set of blueprints that define how to build that house. Right? Each house built from the same set of blueprints is a separate object. Each one is separate from the others. If your neighbor has a house that looks just the same as yours, it’s a different house.

In OOP, we say that we are instantiating from a class (the blueprint) to create a new object.

In Python you do that by calling the class as @mtf showed you above.

The method __init()__ gives us a way to initialize our objects upon creation. We pass in different values (and even objects) to have them setup the object and get it ready to do something.

Therefore, this line of code is:

  1. Creating a new object from the Animal class.
  2. Passing in 2 different pieces of information to define this specific animal. It passes in that animal’s name and age.
  3. The __init__ method runs its code to assign those pieces of information and stores them internal to that animal (its object).

Does that make sense?


#4

Yes :), I’m really starting to see the picture clearly now. However, in step 3 of your answer, the__init__ method is the only function with the name and age parameters but how does python know that “miz” and 7 belong to the name and age variables respectively?


#5

Excellent question.

Short answer is: they are assigned in order, left-to-right.

When you declare a user-defined function or method, you give a name. Then if this function/method requires one or more inputs in order to work, you then declare a list of parameters. Still with me?

The parameter list can be one or more parameters, separated by a comma. You give each a variable name.

As a side note, that variable belongs to the function. It’s scope, meaning who can access it, belongs to that function.

When you want that function to run, you call (invoke) it and pass in the values that it needs to do it’s work. These arguments are assigned in order, left-to-right, to the function’s parameters.

class Animal(object):
     def __init__(self, name, age):
          # code goes here

rhino = Animal('Bob', 38)
  • the object references itself in the first parameter named self. That happens behind the scenes, as Python takes care of it for you
  • 'Bob' is the 1st argument and gets assigned to the name parameter
  • 38 is the 2nd argument and gets assigned to the next parameter from the left, which is age

Does that make sense?

BTW Most programming languages work this way.

Tip:
To improve readability, name your variables purposefully to tell you what data they represent. Name your functions by the expected behavior that will occur when you call it. And name functions starting with a verb, as they are your workers.


#6

And lastly, recall that the order of the arguments dictates the order of the parameters.

def trip_cost(days, city):
    pass

print trip_cost('Tampa', 5)

The function has no control over the order in which the arguments are passed. days will be, 'Tampa', and city will be 5 which will surely trip up the function.


#7

Yes, I understand that it is order sensitive. What if I created another method within the class, called description, that takes the arguments height and weight. Now, both the init method AND the description function have 2 parameters. Now, I create an object of the class that also calls for 2 parameters, how does python know which function to run?


#8

When you create that object, Python automatically calls the __init()__ method. Your other methods need to be called by your code.

For example,

class Animal(object):
     def __init__(self, name, age):
          # code here
  
     def description(self):
          # code here

     def move(self, speed, distance):
          # code here

# creating the object, __init()__ is called
# the arguments are passed in and assigned
# in order to the method's parameters
deer = Animal('Charlie', 3)

# Now we run the description method.
# Notice that no arguments are passed, as
# the method does not have any defined,
# other than a reference to itself.
deer.description()

# Now we make the deer run. The 2
# arguments are passed in to the method
# we called and assigned in order.
deer.move('fast', 20)

To answer question:
You call the methods and pass the arguments. That’s how Python knows what to run and where to assign the arguments.

The exception is the Magic method __init()__, which is called automatically. The double underscores tell you that it’s one of those magical methods.

Does that make sense?


#9

Yes! That makes sense. Quick question, when you typed deer.run() did u mean to call the deer.move() function?


#10

I did. Thank you for pointing that out and excellent catch. It’s now been corrected.


#11

Thank you for all of your help! :slight_smile: It’s exponentially clearer to me now.


#12

You’re welcome.

You learned a fundamental part of programming that works in nearly all languages:

  • Your code declares and defines the list of function/method parameters
  • Then when you call (invoke) that function/method, you are passing in the information (values, dataset, object, etc.) to be worked on.
  • Those arguments are aligned in order from left-to-right and matched up with the function’s parameters.
  • An exception to this in Python is in OOP, where the first parameter is a self, an internal reference to the object.

Cheers.


#13

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.