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?

Ptrhonにおけるクラスについて(初学者用)

Posted at

1. カプセル化(Encapsulation)

  • データをクラスの中に隠す仕組み
  • 外から直接アクセスできないようにすることで、安全性が高まる

🔐 例:__(ダブルアンダースコア)で隠す

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.__balance = balance  # ← 外から直接触れない

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

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

    def get_balance(self):
        return self.__balance

account = BankAccount("山田", 10000)
print(account.get_balance())  # OK
# print(account.__balance)  # ← エラーになる(隠れてるため)

📌 補足

  • __balance は「インスタンス変数(隠されたやつ)
  • それを読むための関数 get_balance() を「getter」と呼ぶ
  • set_balance() などの変更用関数を「setter」と呼ぶ
  • getter / setter は概念であって、関数名ではない!

2. クラス変数とインスタンス変数

class SchoolStudent:
    school_name = "中央高校"  # クラス変数(全員共通)

    def __init__(self, name):
        self.name = name          # インスタンス変数(1人1人異なる)
        self.scores = []

    def add_score(self, score):
        self.scores.append(score)

    def average(self):
        return sum(self.scores) / len(self.scores) if self.scores else 0

3. クラスメソッド(@classmethod

  • クラス全体に対しての処理をする関数
  • self ではなく cls を使う
class SchoolStudent:
    student_count = 0

    def __init__(self, name):
        self.name = name
        SchoolStudent.student_count += 1

    @classmethod
    def get_student_count(cls):
        return cls.student_count

SchoolStudent("田中")
SchoolStudent("佐藤")
print(SchoolStudent.get_student_count())  # → 2

4. オブジェクト指向の4大要素

番号 名前 内容
カプセル化 データを隠す。安全に使えるようにする
継承 親クラスの機能を子が受け継ぐ
ポリモーフィズム 同じ関数名でも動きが変わる(例:DogとCatのspeak)
抽象化 本質だけを見せて、余計な中身は隠す

5. ポリモーフィズムの例

class Animal:
    def speak(self):
        print("何か鳴いている")

class Dog(Animal):
    def speak(self):
        print("ワン!")

class Cat(Animal):
    def speak(self):
        print("ニャー!")

animals = [Dog(), Cat()]
for a in animals:
    a.speak()  # クラスによって違う動作になる!

🎯 用語まとめ

用語 意味
インスタンス クラスから作った実体(=生徒)
クラス 設計図(=学校)
オブジェクト インスタンスと同じ意味
メソッド クラス内の関数
インスタンス変数 self.name のように、インスタンスごとに持つ値
クラス変数 全体で共有される値(例:school_name

📌 ポイント

  • self → 生徒(インスタンス)自身のこと
  • cls → 学校(クラス)全体のこと
  • @classmethod → 「全体で共有してる何か」にアクセスしたいとき便利
  • __(ダンダー) → 変数を外部から隠す(カプセル化)
0
0
1

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?