Python7 min read

Python Classes Basics

Learn object-oriented programming with classes.

Michael Brown
December 18, 2025
0.0k0

Create your own data types.

Define Class

```python class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hi, I'm {self.name}")

Create object person1 = Person("Emma", 25) person1.greet() # Hi, I'm Emma ```

Class Attributes

```python class Car: # Class attribute (shared by all) wheels = 4 def __init__(self, brand, color): # Instance attributes (unique to each) self.brand = brand self.color = color

car1 = Car("Toyota", "red") car2 = Car("Honda", "blue")

print(car1.wheels) # 4 print(car1.brand) # Toyota ```

Methods

```python class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount print(f"Deposited ${amount}") def withdraw(self, amount): if amount <= self.balance: self.balance -= amount print(f"Withdrew ${amount}") else: print("Insufficient funds!")

account = BankAccount("John", 1000) account.deposit(500) # Deposited $500 account.withdraw(200) # Withdrew $200 print(account.balance) # 1300 ```

Remember

- Classes are blueprints - self refers to instance - __init__ is the constructor

#Python#Intermediate#OOP