Fundamentals 8 min read

Understanding Python Classes, Special Methods, Inheritance, and Polymorphism

This article explains Python's class definition, the role of the __init__ constructor, special methods like __repr__, __str__, and __add__, how inheritance and abstract base classes work, and demonstrates using super() for method chaining, providing clear code examples throughout.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python Classes, Special Methods, Inheritance, and Polymorphism

The article introduces how to define a Python class, using class Point: def __init__(self, x=0, y=0): self.x = x self.y = y as a basic example, and explains that self is analogous to this in C++/Java.

It shows that special methods (dunder methods) like def __repr__(self): return 'Point({}, {})'.format(self.__x, self.__y) control the string representation shown in the interactive interpreter, while def __str__(self): return '({}, {})'.format(self.__x, self.__y) provides a user‑friendly format.

Operator overloading is demonstrated with def __add__(self, other): return Point(self.__x + other.__x, self.__y + other.__y) , allowing p1 + p2 to produce a new Point instance.

The article then discusses inheritance, presenting an abstract base class class AbstractShape: def area(self): raise NotImplementedError and concrete subclasses class Circle(AbstractShape): def __init__(self, color, r=0.0): super().__init__(color) self.r = r def area(self): return math.pi * self.r * self.r and class Rectangle(AbstractShape): def __init__(self, color, a, b): super().__init__(color) self.a = a self.b = b def area(self): return self.a * self.b .

It highlights that Python lacks built‑in interface enforcement, so abstract classes raise NotImplementedError to simulate abstract methods, and that super() is the recommended way to invoke parent constructors, especially in multiple inheritance scenarios.

Finally, the article notes Python's dynamic nature, allowing methods to be added at runtime (e.g., Circle.area = lambda self: math.pi * self.r * self.r ), and discusses the limitations compared to static languages regarding polymorphism and compile‑time checks.

PythonoopClassespolymorphismInheritanceSpecial Methods
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.