Classes and Objects
Classes:
Uses the keyword
class
To leave for later you use the
pass
keyword
class Vehicle:
pass
How a class template should look like:
class Vehicle:
def __init__(self, body_type, make):
vehicle_body = body_type
vehicle_make = make
# Initiallizing the class:
car1 = Vehicle("jeep", "toyota")
print(car1.vehicle_body)
The above code will fail to print as the object car1
does not have a vehicle_body
attribute. That is where the self
argument comes in. If you modify the variables assigned with self.
before it will initialize itself and you will have access to the varios items in the class
class Vehicle:
def __init__(self, body_type, make):
self.vehicle_body = body_type # Using self
self.vehicle_make = make # To reference itself
# For other objects
# Initiallizing the class:
car1 = Vehicle("jeep", "toyota")
car2 = Vehicle("truck", "mercedes")
# Prints jeep
print(car1.vehicle_body)
# prints mercedes
print(car2.vehicle_body)
The self
keyword is used to reference itself
Technically car1 and car2 are variables but they are pointing to an object in memory
PreviousRevising the Difference between Methods and FunctionsNextClasses Attributes vs Object Attributes
Last updated