A class is a user-defined blueprint from which objects are created. Classes allow for bundling data and functionality in a straightforward way.
With the class as the blueprint, objects for this type of class can be instantiated, which means that you can construct an instance of this class. Instances can then be used in your actual code.
To understand classes, let's consider an example. Let's say you own a car company. When you create a prototype for a car, you are creating a car class. The models Tesla, Honda, Toyota, and Mercedes are all car classes. The actual cars that are then made are the objects that are instantiated based on their classes. When you make a Tesla car, you have to build it based on the tesla blueprint (the car class), and the car that you made is the object. Classes are unique because they allow you to store certain attributes in them. For example, the tesla has a maximum speed of 120 mph. This can be stored as an attribute, or component, of the class.
Classes in python are created as follows:
class Tesla: # use 'class' keyword followed by your class's name maxSpeed = 120
After creating the class, you can create objects that are instances of that class. This is called instantiating a class.
p = Tesla() # assign a variable to the class with parentheses print(p.maxSpeed) # you can access the attributes inside the object
We're going to be using this a lot, so get used to using it.
Dot notation works as the following:
Here's an example
class dot_example: fun = True difficult = False our_example = dot_example() # instantiate the class # would print True print(our_example.fun) # our_example is the object, fun is the attribute # would print False print(our_example.difficult) # our_example is the object # difficult is the attribute
View code on GitHub.