0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでクラスを使用するときのPublic,Protect,Private変数の挙動

Posted at

1. PythonにおけるPublic, Protected, Privateの違い

変数種類 アクセス範囲 説明
Public (name) クラス内・継承先・インスタンス外部からOK 誰でも触れる公開データ
Protected (_name) クラス内・継承先OK(外部も技術的にはアクセス可) 内部用・継承前提データ
Private (__name) クラス内のみ(裏技あり) 完全に隠したいデータ

2. Publicのシチュエーション実例

📖 ユーザープロフィール(公開データ)

要件

  • 名前や年齢は誰でも見れる&更新もOK
  • publicにする
class User:
    def __init__(self, name, age):
        self.name = name   # public
        self.age = age     # public

# インスタンスから自由にアクセス可能
user = User("Taro", 25)
print(user.name)
user.age = 30

3. Protectedのシチュエーション実例

📄 ドキュメントクラス(基底クラス)

要件

  • ドキュメントの内容は外から直接触ってほしくない
  • でも継承クラスでは内容を加工したい
  • protectedにする
class Document:
    def __init__(self, title, content):
        self.title = title
        self._content = content  # protected

    def display(self):
        print(f"タイトル: {self.title}")
        print(self._content)

class SecretDocument(Document):
    def display(self):
        print(f"【極秘】{self.title}")
        print(f"内容: {self._content[:5]}...(省略)")

doc = SecretDocument("極秘資料", "これは極秘資料です")
doc.display()
print(doc._content)  # 触れちゃうけどマナー違反

4. Privateのシチュエーション実例

💰 銀行口座クラス

要件

  • 残高は外から直接触らせたくない
  • 残高変更は専用メソッドを通す
  • privateにする
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # private

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("残高不足")

    def check_balance(self):
        print(f"{self.owner}の残高: {self.__balance}")

account = BankAccount("Taro", 10000)
account.deposit(5000)
account.withdraw(3000)
account.check_balance()

# 直接アクセスは不可
# print(account.__balance)  # AttributeError

# でも裏技で見える
print(account._BankAccount__balance)

5. まとめと設計の考え方

変数種類 説明 おすすめ用途
Public (name) 誰でも触れる 普通のデータ(ユーザー名など)
Protected (_name) なるべく触ってほしくない 継承先が参照する可能性があるデータ
Private (__name) 完全に隠したい 内部ロジック・セキュリティ的に重要なデータ
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?