How should I indent my code to create a new Animal object?


How should I indent my code to create a new Animal object?


Be sure you don’t indent your code that creates a zebra, otherwise it will be considered part of the Animal class code block. The code to create your zebra goes outside of any class code block, which means it will have no indentation.


In the example provided of this exercise:

class Square(object):
  def __init__(self):
    self.sides = 4

my_shape = Square()
print my_shape.sides

Shouldn’t sides be a second argument of the initializing function, like the class created in the exercise itself?

class Animal(object):
  def __init__(self, name): = name
zebra = Animal("Jeffrey")

Since an actual square always has 4 sides, the value of the sides instance variable for all Square objects should be initialized to 4. Therefore, there is no reason for that value to be passed as an argument.

1 Like


Why do we need to set the additional parameter (name) and any other one equal to ‘self.parameter’?

With functions we don’t have to do this, so how is it different here?

The __init__ method of a class is a function that automatically gets called when an instance of the class is created. It serves the special purpose of performing whatever tasks that the programmer deems necessary for the creation of that instance. Usually, but not always, this includes the setting up of instance variables.

The first parameter of a method always refers to the current instance of the class to which it belongs. Conventionally, this parameter is named self, so it is best to use that name. Any parameters that follow that first one are local variables of the method to which they belong. In order for information that is passed to the __init__ method as arguments to be available for later use, that information must be stored or used in some manner that persists after the __init__ method terminates. Quite often this entails the creation of instance variables. That is why we have statements such as this one: = name

The above establishes name as an instance variable. This variable will persist and be accessible even after the __init__ method terminates. Without such a statement, name would be merely a local variable that would not be recognized outside the __init__ method.

Functions that are not methods serve a wide variety of purposes, and that is why most of them do not do what is described above.