python classes & objects

object oriented programming

Quick Intro

  • Object Oriented Programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects (source). OOP allows us to create our own types of data (e.g. str, dict, list) which holds its own attributes and functions.

  • A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. (source)

  • An instance is an object of a class. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

  • By convention, the class name should be Capitalized

  • We can make changes to an object by reassigning the value; e.g., if Mia gains another 2 pounds, just run the query Mia.weight = 12

  • __init__ is a magic method, a function that is called ‘under the hood’ every time the class is used to create an object

  • an object can have multiple values within each attribute assigned through a nested list format; e.g. if a shopping cart class has attributes “items” and “price”, an object can be created by cart1 = ([‘apple', ‘banana’, ‘milk’], [5.99, 2.99, 10.00])


Class Methods and Special Methods

Defining a method

__str__ is a special method that is called during a print() function / custom print() output above

Creating default attribute


Inheritance

  • Inheritance happens when an object is a sub-type of another object

  • Superclass is the class that is inherited from by another class

  • The superclass is written inside the parentheses of the new class when initializing

  • The new class will inherit all the attributes and methods from the superclass, but it will have its own attributes and methods to add or overwrite its inherited ones

  • The superclass does not have to be a built-in class. You can create your own parent class to have your child class inherit from it.

  • Example on right: Room_Types is a sub-class of the superclass List. Room_Types can do everything a List can do AND call out its own methods.