Understanding Classes and Objects in Python: Definitions, Instantiation, Attributes, Methods, Inheritance, Polymorphism, and Encapsulation
This article introduces Python's object‑oriented programming fundamentals, explaining how to define classes, instantiate objects, differentiate class and instance attributes, and use various method types, followed by practical examples of inheritance, polymorphism, and encapsulation to build well‑structured, maintainable code.
In Python, a class is a core concept of object‑oriented programming (OOP) that allows you to create objects with specific attributes and methods, enabling encapsulation, inheritance, and polymorphism for structured and maintainable code.
Defining a class
Use the class keyword followed by the class name (typically in CamelCase) and a colon. The class body contains attributes (data members) and methods (function members).
class Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age # attribute
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")The __init__() method is the constructor called automatically when an object is created to initialize its attributes. The self parameter refers to the current instance and must be the first argument of all instance methods.
Creating objects
After defining a class, instantiate it by calling the class name with parentheses. Access attributes and methods using dot notation.
person1 = Person("Alice", 30)
person1.greet() # Output: Hello, my name is Alice and I am 30 years old.Class attributes vs. instance attributes
Class attributes are defined at the class level and shared by all instances, often used for constants or default values. Instance attributes are defined in the constructor, giving each instance its own copy.
Method types
Instance methods (default) receive self and can modify object state. Class methods use the @classmethod decorator and receive the class ( cls ) as the first argument. Static methods use @staticmethod and receive no implicit first argument.
class MyClass:
class_variable = 0
def __init__(self, value):
self.instance_variable = value
def instance_method(self):
return f"Called instance_method of {self}"
@classmethod
def class_method(cls):
return f"Called class_method of {cls}"
@staticmethod
def static_method():
return "Called static_method"
obj = MyClass(10)
print(obj.instance_method()) # Called instance_method of <__main__.MyClass object at ...>
print(MyClass.class_method()) # Called class_method of
print(MyClass.static_method())# Called static_methodInheritance
Inheritance lets a class acquire attributes and methods from another class, promoting code reuse and hierarchical design. Subclasses can override parent methods for specific behavior.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!Polymorphism
Polymorphism allows different classes to be used interchangeably through a common interface, typically via method overriding or duck typing.
class Cat(Animal):
def speak(self):
return "Meow!"
def make_animal_speak(animal):
print(animal.speak())
make_animal_speak(Dog()) # Output: Woof!
make_animal_speak(Cat()) # Output: Meow!Encapsulation
Encapsulation hides an object's internal representation, exposing only a limited interface. Private attributes (prefixed with double underscores) can be accessed via public getter and setter methods.
class BankAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.__balance = balance # private attribute
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
account = BankAccount("Alice")
account.deposit(100)
print(account.get_balance()) # Output: 100.0Conclusion
By mastering these basic concepts—class definition, object creation, attribute types, method varieties, inheritance, polymorphism, and encapsulation—you can effectively use classes and objects in Python, and later explore advanced features such as composition, abstract base classes, and decorators, while adhering to solid design principles.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.