1
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 3 エンジニア認定基礎試験 合格に向けて part9 (クラス)

1
Posted at

Pythonクラス基礎まとめ

ここでは、これまで出てきたクラスやメソッドの基礎的な考え方を整理していきます。


1. クラスとインスタンス

Python では クラス を定義して、その設計図から インスタンス を作ることができます。

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(3.0, -4.5)
print(x.r, x.i)  # 3.0 -4.5
  • __init__コンストラクタ で、インスタンス生成時に呼ばれる特別なメソッド。
  • self には作られた インスタンス自身 が渡される。
  • x = Complex(3.0, -4.5) としたとき、3.0-4.5realpartimagpart に入る。selfx そのもの。

2. self とは何か?

class Test:
    def __init__(self, a):
        if a == 123:
            print("init呼ばれた")

t = Test(123)

ここでは t = Test(123) と呼ぶと:

  1. Test クラスからインスタンスを生成
  2. そのインスタンスを self として __init__ に渡す
  3. 引数 123a に入る

→ 結果 "init呼ばれた" が出力される。

selfインスタンス自身を指すもの。左辺の tself に対応するイメージ。


3. メソッドと関数の違い

def standalone():
    print("ただの関数")

class A:
    def method(self):
        print("インスタンスメソッド", self)
  • 関数: クラスの外に定義される。standalone() のように単独で呼ぶ。
  • メソッド: クラスの中に定義される。インスタンスやクラスと結びつき、self などを通じて内部データにアクセスできる。

つまり:

  • 関数は「独立した処理」
  • メソッドは「オブジェクトに結びついた処理」

4. メソッドオブジェクト

class A:
    def hello(self):
        return "hello world"

x = A()
xf = x.hello
print(xf())  # hello world

ここで x.hello は「メソッドオブジェクト」。

  • xf = x.hello で変数に代入しても、あとから xf() と呼べる。
  • このときも self には x が渡される。

一方:

f = A.hello
f()        # エラーになる(self がないため)
f(A())     # OK(明示的にインスタンスを渡す)

クラスから直接メソッドを呼び出すと self は自動で補われないので、自分で渡す必要がある。


まとめ

  • クラスは設計図、インスタンスはその実体。
  • __init__ に渡す引数はインスタンス生成時に指定する。
  • self はインスタンス自身を指す。
  • 関数とメソッドの違いは「クラスに属しているかどうか」。
  • メソッドは変数に代入してあとから呼び出すこともできる。

→ クラスを使うと「データと処理をひとまとまりで管理」できるのが大きな利点!

1
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
1
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?