Python OOP
Splitting a larger task into smaller pieces.
Classes are blueprints (attributes + methods) to build objects
# A potential blueprint for a waiter (an object)
class WaiterBlueprint:
# attributes (variables) are:
is_holding_plate = True
tables = [4, 5, 6]
# methods (functions) are:
def take_order():
...
def handle_payments():
...
# this whole code serves as a blueprint, which makes it a class
waiter = WaiterBlueprint()
# Pascal case for each word, no underscores
# The parenthesis is just to construct an object.Getting attributes and methods from an object
car.speed
car.weight
# where car is the object, and speed/weight are variables.
car.stop()
# where car is the object, and stop() is a functionMake objects and play with them
car = CarBlueprint()
print(car.speed) # using attributes (variables)
car.move() # using methods (functions)Prevent “indent expected” error
class MyClass:
passInitialising using constructors
__init__ function
Set variables, counters, etc., to their starting values when an object is being initialised.
class Car:
def __init__(self):
print("new user being created")
# init function is going to be called everytime you construct an object from this class.Setting attributes
# SELF is just the OBJECT that will be made
class Car:
def __init__(self, seats, windows): # PARAMETERS
self.chair = seats # ARGUMENTS
self.windows = windows
# always have the SELF parameter, which is the actual object being created.
# name of attribute does not need to match parameter name, but should.
my_car = Car(5, 6)
# always pass in the argument for the additional parameters in our init function.
# the longer tedious method would be:
class Car:
pass
my_car = Car()
my_car.chair = 5
my_car.windows = 6Default attribute values
class User:
def __init__(self, user_id):
self.id = user_id
self.followers = 0
user_1 = User("001")
print(user_1.followers) # gives you 0Setting methods
class Car:
def enter_race_mode(self):
self.seats = 2
my_car.enter_race_mode()
# another example
class User:
def __init__(self):
self.following = 0
def follow(self, user):
user.following += 1
self.following += 1
user_1 = User()
user_2 = User()
user_1.follow(user_2)
# both user's following attribute is now 1.Class inheritance
Inheriting attributes and methods between different classes.
Inheriting the initialization
class Fish(Animal):
def __init__(self):
super().__init__()
# inheriting a fish class from the animal class
# for example
class Animal:
def __init__(self):
self.num_eyes = 2
def breathe(self):
print("Inhale, Exhale")
class Fish(Animal):
def __init__(self):
super().__init__()
# taking something from the Animal class
def breathe(self):
super().breathe()
print("while in water")
# taking something from the Animal class and building on it!
def swim(self):
print("Moving in water")See next
- Python-Functions — methods are functions on classes
- Python-Scope-and-Namespace —
selfand attribute scope