Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Defining Private Attributes | Section
/
Object-Oriented Programming in Python

bookDefining Private Attributes

メニューを表示するにはスワイプしてください

Private attributes represent the strongest level of data protection in Python's encapsulation model. By using double underscores, they activate Python's name mangling mechanism, transforming sensitive attributes into nearly inaccessible identifiers. This provides robust protection against accidental interference and helps create secure, professional class designs.

example.py

example.py

copy
Note
Note

Although private attributes can technically be accessed through their mangled names, doing so violates encapsulation and should never be used in production code.

A private attribute like __balance in BankAccount is automatically renamed to _BankAccount__balance through name mangling. This makes it harder to access directly and discourages external use.

Private attributes secure sensitive state and ensure interaction only through validated public methods. In classes like Wallet or BankAccount, data such as balance, PIN, and transaction history stay private, while methods like deposit(), withdraw(), and authenticate() enforce rules and maintain security.

question mark

What is the main purpose of private attributes in Python?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  24

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  24
some-alt