Lesson 1
Revisiting the Building Blocks: Python Classes and Object-Oriented Essentials
Lesson Overview

Greetings! Today, we're revisiting Python classes, the core building block of Object-Oriented Programming (OOP) in Python. Through hands-on examples, we'll revisit the fundamental concepts of Python classes, including their structure, attributes, and methods.

Python Classes Refresher

Let's begin with a refresher on Python classes. Essential to OOP, Python classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific attributes (such as health or strength) and methods (such as attack or defense).

Python
1class GameCharacter: 2 # constructor method 3 def __init__(self, name, health, strength): 4 self.name = name # attribute 5 self.health = health # attribute 6 self.strength = strength # attribute 7 8 def attack(self, other_character): # method 9 other_character.health -= self.strength

Python classes facilitate the grouping of associated code elements, simplifying their management. Now, to better remind ourselves how the above example works, let's go through it step-by-step.

Structure of a Python Class

A Python class serves as a blueprint consisting of attributes and methods. While attributes represent data relevant to a class instance, methods are actions or functions that manipulate this data. Each class includes an __init__ function, also known as a constructor, which is used to define class attributes.

An essential keyword within these methods is self, which represents the class instance. In object-oriented programming, it's needed to access the class's attributes and methods. When a new class instance is created, Python automatically passes it to the self parameter to access individual instance attributes and methods using the self keyword. This mechanism allows each object to keep track of its own state and behaviors.

Python
1class GameCharacter: 2 # constructor: defines class attributes 3 def __init__(self, name, health, strength): 4 self.name = name # attribute 5 self.health = health # attribute 6 self.strength = strength # attribute 7 8character = GameCharacter("Hero", 100, 20) # object or instance of the class
Class Attributes

Attributes in Python classes hold data associated with each class instance. For example, in our GameCharacter class, name, health, and strength are attributes. You can access a class attribute using the object of the class, followed by a dot (.), and then the attribute name.

Python
1class GameCharacter: 2 # constructor: defines class attributes 3 def __init__(self, name, health, strength): 4 self.name = name # attribute 5 self.health = health # attribute 6 self.strength = strength # attribute 7 8character = GameCharacter("Hero", 100, 20) # object or instance of the class 9print(character.name) # prints: Hero 10print(character.health) # prints: 100 11print(character.strength) # prints: 20

Attributes differentiate one class instance from another and store the state of the instance.

Class Methods

A class also contains methods - actions or functions that manipulate the data in the class. For example, the attack method in our GameCharacter class simulates an attack by one game character on another.

Python
1class GameCharacter: 2 # constructor: defines class attributes 3 def __init__(self, name, health, strength): 4 self.name = name # attribute 5 self.health = health # attribute 6 self.strength = strength # attribute 7 8 def attack(self, other_character): # method 9 other_character.health -= self.strength # modifies 'other_character's health attribute 10 11character_1 = GameCharacter("Hero", 100, 20) # First instance of GameCharacter 12character_2 = GameCharacter("Villain", 80, 15) # Second instance 13 14print(character_2.health) # prints: 80 15character_1.attack(character_2) # character_1 attacks character_2 16print(character_2.health) # prints: 60, health decreased after attack
Examples of Python Classes, Attributes, and Methods

To deepen our understanding of Python classes, let's explore another example where we build a basic BankAccount class. This class will demonstrate how we can model real-world entities using object-oriented programming by defining attributes like account holder's name and balance, and methods for depositing and withdrawing money.

Python
1# Define the BankAccount class 2class BankAccount: 3 # Constructor with a default balance of 0 4 def __init__(self, holder_name, balance=0): 5 self.holder_name = holder_name 6 self.balance = balance 7 8 # Method to deposit money 9 def deposit(self, amount): 10 if amount > 0: 11 self.balance += amount 12 print(f"{amount} deposited. New balance: {self.balance}") 13 else: 14 print("Deposit amount must be positive.") 15 16 # Method to withdraw money 17 def withdraw(self, amount): 18 if 0 < amount <= self.balance: 19 self.balance -= amount 20 print(f"{amount} withdrawn. Remaining balance: {self.balance}") 21 else: 22 print("Insufficient balance for the withdrawal or amount is not positive.") 23 24# Create an instance of BankAccount 25account = BankAccount("Alex", 1000) # An account with initial balance of 1000 26 27# Perform some transactions 28account.deposit(500) # Deposit money 29account.withdraw(200) # Withdraw money 30print(f"Final balance in {account.holder_name}'s account: {account.balance}")

This example further illustrates how classes effectively encapsulate data (attributes) and functionalities (methods), enabling us to mimic real-life scenarios. Here, the BankAccount class allows the creation of objects representing bank accounts, emphasizing the powerful organizational benefits of using classes in Python.

Lesson Summary and Practice

Great work revisiting Python classes, their attributes, and methods. Python classes help organize your code, improving its readability and manageability. Now, test your understanding with exercise problems to solidify your newly refreshed knowledge. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.