Loading lessons...
OOP and Classes
OOP and Classes
Object-oriented programming (OOP) organizes code around objects: bundles of data and behavior. Classes are the blueprints.
Class vs object
- A class is a blueprint, like a cookie cutter.
- An object is one thing made from that blueprint, like a cookie.
Classes in Python
Python supports OOP and has been object-oriented from the start. Everything is an object, even numbers and strings.
x = "hello"
print(type(x)) # <class 'str'>
Even "hello" is an object of the class str.
Create a class
class MyClass:
x = 5
Create an object
p1 = MyClass()
print(p1.x) # 5
The class keyword
class Name: starts a class definition. The body holds attributes and methods.
Why OOP?
- Groups related data and code.
- Reuses code through inheritance.
- Models real-world things: a Car, a User, a BankAccount.
TL;DR
- A class is a blueprint; an object is made from it.
class Name:defines a class.obj = Name()creates an object.- Everything in Python is an object.