Classes and Objects
Object-Oriented Programming (OOP) organizes code into objects that contain data (attributes) and behavior (methods). Python is an OOP language, and everything is an object. The fundamental building block is the class, which is a blueprint for creating objects.
Defining a Class
Use the `class` keyword. The `__init__` method is the constructor, called when an object is created.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
Creating Objects (Instances)
Instantiate a class by calling it like a function.
my_dog = Dog("Rex", 3)
print(my_dog.name) # Rex
print(my_dog.bark()) # Rex says woof!
Instance Attributes vs Class Attributes
Instance attributes are defined in `__init__` with `self`. Class attributes are shared across all instances.
class Car:
wheels = 4 # class attribute
def __init__(self, brand):
self.brand = brand # instance attribute
Two Minute Drill
- Classes define blueprints for objects; `__init__` initializes instance attributes.
- `self` refers to the current instance.
- Instance attributes are unique per object; class attributes are shared.
- Methods are functions defined inside a class.
Need more clarification?
Drop us an email at career@quipoinfotech.com
