Classes
Classes are templates for creating objects,
they have attributes, which are like variables, and methods, which are functions tied to
that specific class. Classes are created using the class
keyword.
class Car:
range = 250
We can now create an object from this class and access its properties.
class Car:
range = 250
car = Car()
print(car.range)
Classes can have functions tied to them, known as methods, that we can call on each individual object.
class Car:
range = 250
def drive(self):
self.range = 0
car = Car()
car.drive()
The parameter self
is referring to the instance of the object itself, it lets us access other
properties and methods from the class.
Class properties are mutable and may be reassigned at any given time. Attributes defined in the class are shared by all objects, while attributes defined the constructor are unique to each object.
class Car:
range = 250
def __init__(self,year):
self.year = year
Constructors
Every class has a special method: __init__
that runs once when the class is being created,
called a constructor method.
class Car:
range = 250
def __init__(self,year):
self.year = year
def drive(self):
self.range = 0
car = Car(2018)
print(car.year)
Inheritance
Since classes are like blueprints for objects, they can inherit properties and methods from other classes.
class Car:
range = 250
def __init__(self, year):
self.year = year
def drive(self):
self.range = 0
class ElectricCar(Car):
charge = 100
def __init__(self, year):
super().__init__(year)
ElectricCar
inherits all the methods and properties from its parent class Car
. In classes that
inherit other classes, the parent class can be referred to using super()
.