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.
The article introduces how to define a Python class, using
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = yas 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 NotImplementedErrorand 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.rand
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.
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.
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.
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.
