Flexible initialization

We can make our class initialization more general by putting extra parameters into it, use __init__(self, parameter1, parameter2...) for greater flexibility.

Rewrite Apple class again:

class Apple:
    def __init__(self, inColor):
        self.color = inColor

    def say(self):
        print("I'm an apple.")

Here inside __init__() method, the inColor refers to the value passed into the method, and we assign this value to instance variable using the self parameter, with the code

self.color = inColor

When we create new instances of the class, we do not explicitly call the __init__ method but pass the arguments values in the parentheses following the class name like:

# create two new instance objects of Apple class:
apple2 = Apple('red') 
apple3 = Apple('green')

# access the attributes of the new objects:                  
print(apple2.color)      # red
apple2.say()             # I'm an apple.

print(apple3.color)      # green
apple3.say()             # I'm an apple.

apple2 and apple3 are both new instance objects of Apple class. You can see the initialization function in action when accessing the attributes of the objects, they have different initial states: apple2 has color 'red', apple3 has color 'green'. They all have method say().

To create and initialize a new object

# wrong way
obj = MyClassName()
obj.__init__(args...)

# right way
obj = MyClassName(args...)

Summary:

The special significance of __init__() method is more clear: when we create new instances of a class, Python automatically calls __init__() right away and pass the arguments values in the parentheses following the class name to initialize the new object.

===((need below or not???

)) if need use Apple class as example))

Input argument and instance variable can have the same name, but they are different variables

Noticed? Here, in the header line we define the __init__ method as taking input parameters color and eyeNumber (along with the usual self).

Inside __init__, we just create two new instance variables (fields) also called color and eyeNumber using code self.color self.eyeNumber.

The self indicates the object itself, so self.color, self.eyeNumber makes it clear that the color, eyeNumber after dots are instance variables.

The dotted notation self.variable allows us to differentiate between the two different kinds of variables: the instance variables and the input parameters. It won't be confusing to use the same name for them. It's also a very common and a convention to do so.

results matching ""

    No results matching ""