Tuesday, August 6, 2013

A Quick Tip - Initializing

     In our Ball.py program, we created the attributes after the object was created. However, there's a way to create the attributes, or properties, when the object is being created. It's called initializing, with the __init__() function.

     I'm not quite sure (yet) how useful adding properties to an object when it's created is, But we might find a use for it in future articles.

     Remember: this function uses four underscores (_) and not just two!

     Alright, let's make a copy of our ball program, but this time, we will use __init__().

class Ball2:

    def __init__(self, color, size, direction):
        self.color=color
        self.size=size
        self.direction=direction

    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

theBall=Ball2("yellow", "large", "down")

print("The ball has been loaded.")
print("The ball is", theBall.color)
print("The ball is", theBall.size)
print("The ball is going", theBall.direction)
print("Let's bounce the ball.")
theBall.bounce()
print("The ball is now going", theBall.direction)

     It will run exactly the same as our first ball program. This will be a handy tip later on! I'm sure of it!

No comments:

Post a Comment