-
Notifications
You must be signed in to change notification settings - Fork 0
OOP Concepts
This page is a reference for the Object-Oriented Programming concepts I'm learning and practicing in Python.
A class is a blueprint for creating objects.
Classes can contain attributes and methods that describe what an object has and what it can do.
Example projects where I use classes:
Pet SimulatorEmployee Payroll SystemStudent Grade SystemRecipe BookLibrary System
An object is an instance of a class.
For example, if Pet is a class, an individual pet created from that class is an object.
Objects can have their own data while using the same structure from the class.
The __init__() method runs when a new object is created.
It is commonly used to give an object its starting attributes.
Example:
class Pet:
def __init__(self):
self.hunger = 50
self.happiness = 50self refers to the current object.
It allows each object to access and change its own attributes and methods.
For example:
self.hunger
self.happiness
self.nameAttributes store information about an object.
For example, a Pet object might have:
name
hunger
happiness
energy
Different objects can have different values for the same attributes.
Methods are functions that belong to a class.
They can be used to make an object perform an action or change its data.
For example, a pet could have methods such as:
feed()
play()
sleep()
update_state()
Encapsulation is the idea of keeping data and the methods that work with that data together inside a class.
It can also be used to control how certain data is accessed or changed.
Inheritance allows one class to use attributes and methods from another class.
For example:
Animal
↓
Pet
↓
Dog
A Dog class could inherit common features from Pet instead of having to recreate everything.
Polymorphism allows different classes to use the same method name while behaving differently.
For example, different types of pets could all have a:
make_sound()
method, but each type of pet could produce a different result.
Composition is when one class contains or uses objects from another class.
For example, a Library could contain multiple Book objects.
Library
├── Book
├── Book
└── Book
This is useful for building larger programs out of smaller classes.
Python lists can store multiple objects from a class.
For example, a library could have:
books = [book1, book2, book3]
This is useful when building systems with multiple students, employees, books, pets, or other objects.
ClassesObjects__init__()self- Attributes
- Methods
- Encapsulation
- Inheritance
- Polymorphism
- Composition
- Lists of objects
- Multiple classes working together
- Larger OOP projects
Pet Simulator Game