【Python】 Python ~ 基本編 / クラス・継承 ~

■ はじめに

Pythonのクラスについて、扱う。
なお、クラスじゃないが、Nullについても扱う。

目次

【0】Null
【1】クラス
【2】継承
【3】namedtuple (名前付きタプル)
【4】Context Managers(コンテキストマネージャ)

【0】Null

* Python は「None」となっている

Null チェック

value = None

if value is not None:
  print('Not Null')
else:
  print('Null')

 【1】クラス

* メソッド定義は、 def を使う
* コンストラクタは、__init__ メソッドとして定義する
* デストラクタは、__del__メソッドとして定義する
* 第一引数にselfを指定する必要があり、それぞれのインスタンスをさす
    + Javaの this にあたる
* 第二引数からユーザー定義のパラメータになる
* デフォルトの値がある場合は、=<値> で指定可能

 サンプル

# coding: UTF-8

class Person:
    # コンストラクタ
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sayHello(self):
        print("Hello, %s!" % (self.name))

tom = Person("Tom", 23)
tom.sayHello()
print(tom.name)

privateなプロパティ / メソッド

* プロパティもメソッドも「__」を付ければいい

クラスメソッド

  • java/C#のstaticメソッドみたいなもの?
class Hello:
    @classmethod # デコレータって機能
    def say_hello(cls):
        return "Hello"

Hello.say_hello() 

Python ~ 基本編 / デコレータ @xxxx ~
https://dk521123.hatenablog.com/entry/2020/05/19/000000

 【2】継承

* 「class 【クラス名】(【継承したいクラス】):」で継承
* 多重継承可能
   => 「class 【クラス名】(【継承したいクラス1】, ... ,【継承したいクラスn】):」で多重継承

  使用上の注意

* オーバーロード(引数違いのメソッドを定義する)はサポート外

  サンプル

Person クラスを継承して、Employee クラスを定義

# coding: UTF-8

class Person(object):
    def __init__(self, name):
        self.name = name
    def sayHello(self):
        print("Hello, %s!" % self.name)

class Employee(Person): # ★ここに注目★
    def work(self):
        print("%s is working" % self.name)
        
tom = Employee("Tom")
tom.sayHello()
tom.work()
print(tom.name)

親クラスのメソッド呼び出し

class Greeting:
    def __init__(self):
        self.message = "Hello"
        self.name = "Mike"

    def say_hello(self):
        print(self.message + " " + self.name)

class Hello(Greeting):
    def say_hello(self):
        super().say_hello()
        print("Hello World!")

hello = Hello()
hello.say_hello()

出力結果

Hello Mike
Hello World!

【3】namedtuple (名前付きタプル)

簡易クラスを作成できる namedtuple (名前付きタプル)については、
以下の関連記事を参照のこと

Python ~ namedtuple / 簡易クラス ~
https://dk521123.hatenablog.com/entry/2020/11/10/134233

【4】Context Managers(コンテキストマネージャ)

Java の try-with-resources 、C# の using みたいなことができる

サンプル

class ContextManagerDemo:
  """ Context Manager for sample
  """

  # 参考:コンストラクタ
  def __init__(self):
    print('__init__')

  def __enter__(self):
    """ Enter
    初期化として使える
    """
    print('__enter__')
    # ★「return self」必要!! ★
    return self

  # 参考:public method
  def hello_world(self):
    print('hello_world')

  def __exit__(self, exc_type, exc_value, traceback):
    """Exit
    例外が起きてもくる
    """
    print('__exit__')

  # 参考:ディストラクタ
  def __del__(self):
    print('__del__')

if __name__ == '__main__':
  with ContextManagerDemo() as context:
    print('start')
    context.hello_world()
    print('after calling hello_world()')
    raise Exception('error')
    print('Not calling')

出力結果

__init__
__enter__
start
hello_world
after calling hello_world()
__exit__
Traceback (most recent call last):
  File "c:/Users/Daisuke/Documents/Python Scripts/hello.py", line 36, in <module>
    raise Exception('error')
Exception: error
__del__

  参考文献

http://python.keicode.com/lang/oop-basics.php

  動画

クラス
http://dotinstall.com/lessons/basic_python_v2/26022
継承
http://dotinstall.com/lessons/basic_python_v2/26023
補足

* Pythonのver2.x => ver3.x で文法が変わったので、
   参考文献の動画のサンプルが動かなかった。
   => 原因は「print文に括弧が必要だったこと」

http://oshiete.goo.ne.jp/qa/4970161.html

関連記事

Python ~ 基本編 / 抽象クラス ~
https://dk521123.hatenablog.com/entry/2021/11/28/113711
Python ~ namedtuple / 簡易クラス ~
https://dk521123.hatenablog.com/entry/2020/11/10/134233
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / ファイル読込・書込 ~
https://dk521123.hatenablog.com/entry/2019/10/07/000000
  Python ~ 基本編 / コメント・制御文編 ~
https://dk521123.hatenablog.com/entry/2019/08/25/000330
Python ~ 基本編 / デコレータ @xxxx ~
https://dk521123.hatenablog.com/entry/2020/05/19/000000