Master Python Object‑Oriented Programming: From Basics to Advanced Techniques
This comprehensive guide explains the differences between procedural and object‑oriented programming in Python, introduces class creation, instance, class and static methods, inheritance, polymorphism, magic methods, and property decorators, and provides numerous runnable code examples to illustrate each concept.
Procedural vs Object‑Oriented Programming
Procedural programming follows a linear sequence of steps: import libraries, define global variables, write functions, and finally a main function as the entry point. In contrast, object‑oriented programming (OOP) encapsulates data and behavior into classes, which become the fundamental building blocks of a program.
Basic Class Usage
Define a class with class, provide an __init__ constructor, and implement methods that operate on instance attributes.
class Student:
def __init__(self, idx):
self.idx = idx
def runx(self):
print(self.idx)
time.sleep(1)
a = Student('a')
a.runx()Key OOP Concepts
Encapsulation : Data and the functions that manipulate it are bundled together inside a class, protecting the internal state from external interference.
Inheritance : A subclass derives attributes and methods from a parent class, allowing code reuse and hierarchical design.
Polymorphism : Different subclasses can implement the same method name, and the correct version is chosen at runtime based on the object's actual type.
Abstraction : Classes expose a clear interface while hiding implementation details.
Inheritance Example
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
cat = Cat()
for obj in (dog, cat, Animal()):
obj.run()Magic (Special) Methods
Python provides a set of "magic" methods that enable custom behavior for built‑in operations such as object creation ( __init__), representation ( __repr__), attribute access ( __getattr__, __setattr__), iteration ( __iter__), length ( __len__), arithmetic ( __add__, __sub__, …), and callable objects ( __call__).
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
def __str__(self):
return f'Vector ({self.a}, {self.b})'
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)Property Decorator
The @property decorator turns a method into a managed attribute, allowing custom getter, setter, and deleter logic while keeping a natural attribute‑like syntax.
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if isinstance(value, int):
self.__age = value
else:
raise ValueError('Age must be an integer')
@age.deleter
def age(self):
print('Age attribute deleted')
p = Person('Alice', 30)
print(p.age)
p.age = 31
print(p.age)
del p.ageUsing property() Function Directly
Alternatively, the built‑in property() function can create a managed attribute by passing getter, setter, deleter, and docstring.
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self, age):
if isinstance(age, int):
self.__age = age
else:
raise ValueError('Age must be integer')
def del_age(self):
print('Age attribute deleted')
age = property(get_age, set_age, del_age, 'Age of the person')
obj = People('Bob', 25)
print(obj.age)
obj.age = 26
print(obj.age)
del obj.ageAccess Control with Private Members
Prefixing an attribute with double underscores makes it name‑mangled (e.g., self.__age becomes self._ClassName__age), effectively hiding it from external access while still allowing controlled interaction via class methods.
class Secret:
__secret = 42
@classmethod
def reveal(cls):
print(cls.__secret)
Secret.reveal()All the above concepts together provide a solid foundation for writing clean, maintainable, and extensible Python code using object‑oriented principles.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
