0Pricing
Python For Kids · レッスン

クラスとオブジェクトを作成する

初めてのPythonクラスを作成します。

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

クラスとオブジェクトの作成

オブジェクト指向プログラミング(OOP)のレッスンへようこそ。ここでは、Pythonで自分のクラスとオブジェクトを作成する方法を学びます。クラスとオブジェクトを使うと、関連するプロパティと振る舞いをまとめてコードを整理できます。

クラスとオブジェクトを作成する — イラスト1

クラスとは

クラスは、オブジェクトを作成するための設計図のようなものです。クラスから作成されるオブジェクトが持つプロパティ(属性)と振る舞い(メソッド)を定義します。

  • 属性: オブジェクトの特徴(色、サイズなど)です。
  • メソッド: オブジェクトが実行できる動作(移動、発話など)です。

クラスをレシピ、オブジェクトをそのレシピから作られる料理だと考えてみてください。

Pythonでのクラスの定義

Pythonでは、class キーワードに続けてクラス名とコロンを記述することで、クラスを定義できます。クラスの内部では、属性とメソッドを定義します。

構文:

class ClassName:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    def method_name(self):
        # Code for the method
        pass

__init__ メソッド

__init__ メソッドは、Pythonのクラスにおける特殊なメソッドです。クラスから新しいオブジェクトを作成するときに呼び出され、オブジェクトの属性を初期化するために使用されます。

例:

# Defines the Person class with name and age attributes
class Person:
    def __init__(self, name, age):
        self.name = name  # Sets the name of the person
        self.age = age    # Sets the age of the person

クラスからのオブジェクトの作成

クラスを定義すると、関数と同じようにクラス名を呼び出して、そこからオブジェクト(インスタンス)を作成できます。

例:

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

# Accesses the object's attributes
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 12

クラスへのメソッドの追加

メソッドはクラスの内部に定義する関数で、そのクラスから作成されたオブジェクトの振る舞いを表します。

例:

# Defines the Person class with a greet method
class Person:
    def __init__(self, name, age):
        self.name = name  # Sets the name of the person
        self.age = age    # Sets the age of the person

    def greet(self):
        print("Hello, my name is " + self.name + "!")  # Prints a greeting message

# Creates an object of the Person class
person1 = Person("Bob", 15)

# Calls the greet method of the object
person1.greet()  # Output: Hello, my name is Bob!

プログラム例: シンプルなクラスの構築

クラスとオブジェクトの仕組みを理解するため、属性とメソッドを持つシンプルな Car クラスを作成します。

コード:

# Defines the Car class
class Car:
    def __init__(self, make, model, color):
        self.make = make    # Sets the make of the car
        self.model = model  # Sets the model of the car
        self.color = color  # Sets the color of the car

    def display_info(self):
        print("Car Make:", self.make)    # Prints the make of the car
        print("Car Model:", self.model)  # Prints the model of the car
        print("Car Color:", self.color)  # Prints the color of the car

    def paint(self, new_color):
        self.color = new_color  # Changes the color of the car
        print("The car has been painted to", self.color)  # Confirms the color change

# Creates an object of the Car class
my_car = Car("Toyota", "Corolla", "Red")

# Calls the display_info method
my_car.display_info()
# Output:
# Car Make: Toyota
# Car Model: Corolla
# Car Color: Red

# Calls the paint method to change the car's color
my_car.paint("Blue")
# Output: The car has been painted to Blue

# Displays the updated car information
my_car.display_info()
# Output:
# Car Make: Toyota
# Car Model: Corolla
# Car Color: Blue

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

Pythonのクラスでは、変数を次のように分類できます。

  • インスタンス変数: 各オブジェクトのインスタンスに固有の変数です。
  • クラス変数: クラスのすべてのインスタンスで共有される変数です。

この2種類の変数の使い方を見てみましょう。

# Defines the Student class with a class variable
class Student:
    school = "XYZ High School"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

    def display_info(self):
        print(self.name + " attends " + Student.school)  # Prints student info

# Creates two objects of the Student class
student1 = Student("Alice")
student2 = Student("Bob")

# Calls the display_info method for both students
student1.display_info()
student2.display_info()

よくできました!

Pythonでクラスとオブジェクトを作成し、属性とメソッドを定義してコードを効果的に整理する方法を学びました。クラスとオブジェクトの理解は、オブジェクト指向プログラミング(OOP)の基本であり、より複雑で再利用可能なプログラムの構築に役立ちます。自分でクラスを作成し、さまざまな属性やメソッドを試しながら、練習を続けてください。

クラスとオブジェクトを作成する — イラスト10

よくある質問

「クラスとオブジェクトを作成する」レッスンは無料ですか?

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

「クラスとオブジェクトを作成する」で何を学びますか?

初めてのPythonクラスを作成します。 ブラウザで直接実行するハンズオンコードでPython For Kidsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

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

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

「クラスとオブジェクトを作成する」レッスンにはどのくらい時間がかかりますか?

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

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

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

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

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