Python: Encapsulation and Inheritance

Last updated: 2026-09-22

Encapsulation hides the internal details of an object, exposing only safe operational interfaces. Inheritance lets one class automatically have the functionality of another, avoiding repetition. These two concepts are the backbone of object-oriented programming.


Related Built-in Functions:super()

1. Encapsulation and Private Attributes

Encapsulation means that an object's internal data should not be directly accessed from outside — it should be manipulated through methods.

(1) Single Underscore _ — Convention for "Protected" Attributes

▶ Example: Single and Double Underscore

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

A single underscore is just a convention, not enforced — Python won't stop you from accessing it. It's like writing in the documentation "this is internal, don't touch."

(2) Double Underscore __ — Name Mangling

▶ Example: Bank Account Class

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

Double underscores trigger name mangling — __balance is internally transformed to _BankAccount__balance. This isn't true "privacy," just making accidental overriding less likely.

Tip: Python has no true private. It relies on the "we are all consenting adults" understanding — single underscore means "internal use," double underscore prevents name collisions. Other languages (like Java) have a true private keyword; Python doesn't and isn't planning to add one.

▶ Example: Temperature Class (Difficulty: Star-Star)

▶ Try it Yourself

Output:

TEXT 📖 Display only
Temperature cannot be below absolute zero!


2. @property: Elegant Access Control

Writing set_celsius() / get_celsius() is verbose. @property lets you control access while keeping the syntax of attribute access:

▶ Example: Using @property

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

Tip: Advantages of @property: 1) No parentheses needed for access: t.celsius instead of t.get_celsius(). 2) Automatic validation on assignment: t.celsius = value instead of t.set_celsius(value). 3) Can convert a regular attribute to a computed one without breaking existing code.



3. Inheritance

Inheritance lets a child class have all the attributes and methods of its parent class:

▶ Example: Animal Inheritance

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

(1) super(): Calling Parent Methods

▶ Example: super() to Call the Parent

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


4. Mixin Pattern

A Mixin is a special class — not used independently, but "mixed in" to add functionality to other classes:

▶ Example: Mixin Pattern

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully

Tip: Mixin naming convention: Class names ending in Mixin indicate they are for mixing in, not for standalone use. A class can mix in multiple Mixins plus one main base class — much more flexible than deep single inheritance.



5. Common Use Cases


Related Built-in Functions:super()

❓ FAQ

Q When should I use inheritance vs. Mixin?
A Inheritance suits "is-a" relationships — a dog is an animal. Mixins suit "has-a ability" — a duck can swim. Prefer composition (Mixin) over inheritance, as deep inheritance hierarchies are hard to maintain. A good rule: inheritance should not exceed 3 levels.
Q What's the difference between @property and a regular method?
A @property makes a method look like an attribute — no parentheses for access, assignment triggers the setter. It's essentially an "attribute interceptor" — you write code as if manipulating an attribute, but a method actually executes.
Q Does Python support multiple inheritance? Any pitfalls?
A Yes — class C(A, B). However, multiple inheritance has the "diamond problem" (which parent method to use when both have the same name). Python uses MRO (Method Resolution Order), searching left to right. Mixins are a design pattern that leverages multiple inheritance, with Mixin classes being small and functionally independent, avoiding diamond issues.

📖 Summary


📝 Exercises

  1. Beginner (Difficulty: Star): Define a Product class with @property for the price attribute — must be positive when setting; returns the original value when getting.

  2. Intermediate (Difficulty: Star-Star): Define a three-level inheritance: Animal -> Mammal -> Dog / Cat. Animal has name and age; Mammal adds fur_color; Dog and Cat each implement their own speak() method.

  3. Advanced (Difficulty: Star-Star-Star): Create a logging system with LoggableMixin (provides log_info(), log_error() methods) and a base class Application (has a name attribute). Have WebApp and CLIApp both inherit from Application and mix in LoggableMixin to implement logging functionality.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏