tags: Lesson Notes Python OOP PythonFlask2021

Classes

  • So now we went over what the 4 pillars are and we did use classes but just what are they?
  • How do they work?
  • What are they used for?

Blueprints:

  • This is how we will need to start thinking of classes. When we were creating dictionaries we were basically creating a class.
  • Each class has 1st a name to call it by like User, Dog, House
    • Always capitalized
  • After that we need to set up attributes. These are things that the instances (each object) have. Like a User has the attributes of a name, age, email for example
  • Next we have methods. These are things that the instance can do. Like a User can take a walk, have a birthday

Set up the class:

  1. To start we need to declair that we are going to create a class
class House:
  1. Now we need to know how we will create an instance at least to start with
winterHome = House()
summerHome = House()
  1. Next is to add the attributes. Remember that is what each item will have.
class House:
    def __init__(self):
  • Before we go to much further it is important to note that each class will always start like this.
    • Inside the () with self will go things that you will need to declair as you create the instance.
    • Some attributes will not need to be declaired in each instance as it is always the same or is going to be part of a method.
    • I will add both now to our House class
class House:
    def __init__(self, name, street, city, state, zip):
        self.name = name
        self.street = street
        self.city = city
        self.state = state
        self.zip = zip
        self.floors = 2
        self.items = []
  1. Ok now lets create an instance of our house
winterHome = House("Winter Home", "123 1st Street", "Berwick", "PA", 18603)
summerHome = House("Summer Home", "456 2nd Ave", "Virginia Beach", "VA", 23452)
  1. Ok so we have 2 houses now. the self.floors means that every house we create will have 2 floors..this is a set value. The self.furniture is an empty list that we will use a method to add items to the house
    1. 1st lets make a way to print the house
    2. Then lets go ahead and add our stuff to the house
    3. Maybe a way to print our items too
    def printHouse(self):
        print(f"Our {self.name} is located at {self.street} {self.city}, {self.state} {self.zip}.  There are {self.floors}")
    
    def addItems(self,item):
        self.items.append(item)
        
    def printItems(self):
        print(f"Our {self.name} has the following items: {self.items}")
  • Now we need to call these functions
winterHome.printHouse()
summerHome.printHouse()

winterHome.addItems('Couch')
winterHome.addItems('Bed')

summerHome.addItems('Pool')
summerHome.addItems('Grill')

summerHome.printItems()
winterHome.printItems()

So there you have it. Classes with attributes and methods.

Link to Code: