0Pricing
Python For Kids · レッスン

カプセル化

高度なOOPの概念を学びます。

「カプセル化」はCoddyKit上の無料Python For Kidsレッスンです。 これはレッスン4/5です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPython For Kids学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Python For Kidsコースには全5レッスンが含まれています。

カプセル化

オブジェクト指向プログラミング(OOP)のレッスンへようこそ。ここでは、クラス内のデータとメソッドを保護するための重要な概念である、Pythonのカプセル化について学びます。

カプセル化 — イラスト1

カプセル化とは

カプセル化とは、データ(属性)と、そのデータを操作するメソッド(関数)を、クラスという単一の単位にまとめる概念です。また、オブジェクトの一部の要素への直接アクセスを制限し、オブジェクトの内部表現を外部から隠します。

  • データ隠蔽: オブジェクトの内部状態を意図しない干渉から保護します。
  • アクセス制御: データやメソッドへのアクセス方法や変更方法を定義します。

カプセル化により、オブジェクト自身がデータを管理し、必要なものだけを外部に公開できます。

アクセス修飾子

Pythonでは、アクセス修飾子を使ってクラスメンバー(属性とメソッド)の可視性を制御し、カプセル化を実現します。アクセス修飾子には次の3種類があります。

  • Public: どこからでもアクセスできます。
  • Protected: クラス内およびそのサブクラスからアクセスできます。
  • Private: クラス自身の内部からのみアクセスできます。

Pythonでこれらのアクセス修飾子を使用する方法を見てみましょう。

Public属性とメソッド

Publicメンバーは、クラスの外部からアクセスできます。特に指定しない限り、すべての属性とメソッドはデフォルトでPublicです。

例:

# Defines the Person class with public attributes and methods
class Person:
    def __init__(self, name, age):
        self.name = name  # Public attribute
        self.age = age    # Public attribute

    def greet(self):
        print("Hello, my name is " + self.name + "!")  # Public method

# Creates an object of the Person class
person1 = Person("Alice", 30)

# Accesses public attributes and methods
print(person1.name)  # Output: Alice
person1.greet()      # Output: Hello, my name is Alice!

Protected属性とメソッド

Protectedメンバーは、先頭にアンダースコア(_)を1つ付けて表します。クラス内およびそのサブクラスからアクセスできますが、クラスの外部から直接アクセスするべきではありません。

例:

# Defines the Employee class with protected attributes and methods
class Employee:
    def __init__(self, name, salary):
        self._name = name      # Protected attribute
        self._salary = salary  # Protected attribute

    def _increase_salary(self, amount):
        self._salary += amount  # Protected method
        print(self._name + "'s new salary is " + str(self._salary))

# Creates an object of the Employee class
employee1 = Employee("Bob", 50000)

# Accesses protected attributes and methods (not recommended)
print(employee1._name)  # Output: Bob
employee1._increase_salary(5000)  # Output: Bob's new salary is 55000

Private属性とメソッド

Privateメンバーは、先頭にアンダースコア(__)を2つ付けて表します。クラス自身の内部からのみアクセスでき、クラスの外部から直接アクセスすることはできません。

例:

# Defines the BankAccount class with private attributes and methods
class BankAccount:
    def __init__(self, owner, balance):
        self.__owner = owner    # Private attribute
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount  # Modifies private attribute
        print("Deposited:", amount)
        self.__show_balance()

    def __show_balance(self):
        print("Current Balance:", self.__balance)  # Private method

# Creates an object of the BankAccount class
account1 = BankAccount("Charlie", 1000)

# Attempts to access private attributes and methods (will cause errors)
# print(account1.__owner)        # AttributeError
# account1.__show_balance()      # AttributeError

# Uses public methods to interact with private attributes
account1.deposit(500)  # Output:
                        # Deposited: 500
                        # Current Balance: 1500

カプセル化を使う理由

カプセル化には、次のようなメリットがあります。

  • 制御: データへのアクセス方法や変更方法を制御できます。
  • 安全性: オブジェクトの内部状態を意図しない変更から保護できます。
  • 保守性: コードを保守しやすくし、エラーが発生しにくくなります。

カプセル化は、堅牢で安全なアプリケーションの構築に役立ちます。

カプセル化の例:Carクラス

カプセル化を使用して属性とメソッドを保護するCarクラスを作成してみましょう。

コード:

# Defines the Car class with encapsulated attributes and methods
class Car:
    def __init__(self, make, model, year):
        self.make = make          # Public attribute
        self.model = model        # Public attribute
        self.__year = year        # Private attribute

    def get_year(self):
        return self.__year  # Public method to access private attribute

    def set_year(self, year):
        if year > 0:
            self.__year = year  # Public method to modify private attribute
            print("Year updated to", self.__year)
        else:
            print("Invalid year!")

    def __display_info(self):
        print(self.make, self.model, self.__year)  # Private method

    def show_info(self):
        self.__display_info()  # Public method that calls a private method

# Creates an object of the Car class
car1 = Car("Tesla", "Model S", 2020)

# Accesses public attributes and methods
print(car1.make)        # Output: Tesla
print(car1.get_year())  # Output: 2020

# Modifies the private attribute using a public method
car1.set_year(2021)     # Output: Year updated to 2021

# Calls a public method that interacts with a private method
car1.show_info()        # Output: Tesla Model S 2021

# Attempts to access private attributes and methods directly (will cause errors)
# print(car1.__year)         # AttributeError
# car1.__display_info()      # AttributeError
# Defines the Student class with encapsulated attributes
class Student:
    def __init__(self, name, grade):
        self.name = name      # Public attribute
        self.__grade = grade  # Private attribute

    def get_grade(self):
        return self.__grade  # Public method to access private attribute

    def set_grade(self, grade):
        if 0 <= grade <= 100:
            self.__grade = grade  # Updates the grade
        else:
            print("Invalid grade!")

# Creates an object of the Student class
student1 = Student("Diana", 85)

# Accesses and modifies the grade using public methods
print(student1.get_grade())  # Output: 85
student1.set_grade(90)
print(student1.get_grade())  # Output: 90

# Attempts to access the private attribute directly (will cause an error)
# print(student1.__grade)     # AttributeError

よくできました!

Pythonでカプセル化を使用して、クラス内のデータとメソッドを保護する方法を学びました。カプセル化を使うと、オブジェクトのデータへのアクセスを制御できるため、プログラムの安全性と保守性が向上します。適切なアクセス修飾子を使用してクラスを設計し、コーディングスキルをさらに高めていきましょう。

カプセル化 — イラスト10

よくある質問

「カプセル化」レッスンは無料ですか?

はい。「カプセル化」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Python For Kidsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Python For Kidsコースには全5レッスンが含まれています。

「カプセル化」で何を学びますか?

高度なOOPの概念を学びます。 ブラウザで直接実行するハンズオンコードでPython For Kidsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Python For Kidsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのPython For Kidsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/5です。

「カプセル化」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このPython For Kidsレッスンでコードを書いて実行できますか?

はい。すべてのPython For Kidsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. OOP入門
  2. クラスとオブジェクトを作成する
  3. 継承
  4. カプセル化
  5. ポリモーフィズム
← Python For Kidsに戻る