Not all objects you create are going to have the same characteristics, so you need to have the ability to change an attributes value. To do this, you’ll need to use dot syntax:
# changing the value of an attribute class Car( ):
sound = "beep" color = "red" ford = Car( ) print(ford.sound) # will output 'beep'
ford.sound = "honk" # from now on the value of fords sound is honk, this does not affect other instances
print(ford.sound) # will output 'honk'
Go ahead and run the cell. You’ll notice that we’ll output the sound attribute of the ford instance before and after we change it. Using dot syntax, we’re able to assign the sound attribute a new value. This is no different than changing a variables’ value. The ford object’s sound attribute will now be “honk” until we decide to change it.
Using the __init__( ) Method
So far, we’ve been creating classes in a very basic form. When you want to instantiate an object with specific properties, you need to use the initialization (init) method. Whenever an instance is created, the init method is called immediately. You can use this method to instantiate objects with different attribute values upon creation. This allows us to easily create class instances with personalized attributes. Now, we’ll go over methods tomorrow, so don’t worry too much about the syntax, but more so the understanding of how to use this method. The declaration for this method has two underscores before and after the word init. It also includes the “self” keyword (more on this in the next section) inside of the parenthesis as a mandatory parameter. For this example, we’ll create an instance with a color defined at instantiation. Let’s go ahead and try it out:
1| # using the init method to give instances personalized attributes upon creation
3| class Car( ):
4| def __init__(self, color):
5| self.color = color # sets the attribute color to the value passed in
7| ford = Car("blue") # instantiating a Car class with the color blue
9| print(ford.color)
Go ahead and run the cell. We’ll get a resulting output of “blue”. When we create the ford instance, it is initialized with the attribute color set to blue. All of this occurs on the 5th line. When we declare the ford variable to be instantiated, it passed the argument
“blue” into the initialization method immediately. The self argument is ignored and “blue” is passed into the color parameter. Within the init method is where we set our color attribute to the argument that was just passed in. Hence the value “blue.” Keep in mind that parameters for this method work the same as functions and need to be in the correct order.
Do'stlaringiz bilan baham: |