Understanding Classes and Objects in Python
Python supports object-oriented programming through classes and objects. A class defines behavior and data structure, while an object is a concrete instance of that class.
Define a Class
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
print(f"Car Make: {self.make}, Model: {self.model}")__init__() initializes a new instance after it is created. The first parameter, conventionally named self, refers to the instance receiving the method call.
Create Objects
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")
car1.display_info()
car2.display_info()Each object has its own instance attributes.
Instance Attributes vs Class Attributes
Instance attributes belong to one object:
class User:
def __init__(self, name):
self.name = nameClass attributes are shared through the class unless an instance shadows them:
class User:
species = "human"
def __init__(self, name):
self.name = nameUse class attributes for values that conceptually belong to the class as a whole, not mutable per-instance state.
Instance Methods
Methods can read or modify instance state:
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1Encapsulation by Convention
Python does not enforce private instance fields in the same way as some languages. A leading underscore communicates that an attribute is internal:
class Account:
def __init__(self, balance):
self._balance = balanceDouble-underscore names trigger name mangling, but they are primarily intended to avoid accidental subclass collisions rather than provide strong security boundaries.
Properties
Use @property when attribute-like access needs validation or computed behavior:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@property
def fahrenheit(self):
return self.celsius * 9 / 5 + 32Representation
Defining __repr__() makes objects easier to inspect:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __repr__(self):
return f"Car(make={self.make!r}, model={self.model!r})"Conclusion
Classes bundle related state and behavior, while objects represent individual instances. Start with simple instance attributes and methods, introduce class attributes or properties only when they model the domain clearly, and keep class responsibilities focused.