12.2 Init Function

Init Function

Classes are useful in programming because you get to put your own specific values into the class attributes when making an object. That is where the init function comes in. The init function allows for classes to take in values when objects are created, and these values can then be assigned to the class' attributes.
Without the init function, you can't customize your class every time you create an instance. Why would you want to customize? For instance, when you buy a car, you want it to work how you want it to, so you want to be able to choose a max speed and other attributes
Here's an example of how to use it:
class Tesla: def __init__(self, maxSpeed=120, color="red"): # the init function always needs the self keyword # we'll go over the self keyword soon # if no maxSpeed is entered, maxSpeed will default to 120 # if no color is entered, color will default to "red" self.maxSpeed = maxSpeed # set the class' attribute maxSpeed # to the provided maxSpeed self.color = color # set the class' attribute color to the #provided color p1 = Tesla(140, "blue") print(p1.maxSpeed) # will print 140 print(p1.color) # will print "blue"
View code on GitHub.
In the example above, the user creates an instance of the Tesla class with the following customizations: a max speed of 140 and the color blue
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.