LoginSignup
2
5

More than 3 years have passed since last update.

【Python3】他言語エンジニアのためのPythonチートシート《オブジェクト指向編》

Last updated at Posted at 2019-08-14

はじめに

Python以外のプログラミング言語を習得しているエンジニア向けのチートシートです。

オブジェクト指向編と銘打っていますが、オブジェクト指向自体ではなく、
それを実現するために必要なモジュールとクラスの書き方についてまとめています。

※随時更新していきます。

モジュール

組み込みモジュール

import random as rand
print(rand.randint(0, 100))
# >> 77
  • Pythonには標準で多くのモジュールが用意されている

自作モジュール

from hoge import hello_python
hello_python()
# >> ほげ
# >> Hello Python!
hoge.py
def hello_python:
    print("Hello Python!")

print("ほげ")        # import時に実行される

if __name__ == "__main__":
    print("ふが")    # importでは実行されず、直接呼出時に実行される
  • モジュールをインポートすると、そのモジュールのコードは全て実行される

クラス

クラス定義

class Hello:
    count = 0                    # クラスプロパティ

    def __init__(self, lang):    # コンストラクタ(第一引数(self)はインスタンス自身)
        self.__lang = lang       # インスタンスプロパティ
        Hello.count += 1

    def say(self):               # インスタンスメソッド
        print "Hello " + self.__lang + "!"

    @classmethod                 # クラスメソッド
    def say_count(cls):          # 第一引数(cls)はクラス自身
        print("インスタンスは" + cls.count + "個だよ")

    @staticmethod                # スタティックメソッド
    def say_hello():             # 第一引数にselfやclsを取らない
        print("Hello World!")

hello = Hello("Python")          # インスタンス化

hello.say()
# >> Hello Python!

Hello.say_count()
# >> インスタンスは1個だよ

Hello.say_hello()
# >> Hello World!
  • クラスはヘッダーとスイートから成る複合文で、プロパティ(変数・属性)とメソッド(関数)を持つ
  • 慣習として、クラス名は大文字で始まるキャメルケース、プロパティ名・メソッド名は全て小文字でスネークケース
  • クラスプロパティ・クラスメソッドは全てのインスタンスに影響する

継承

class SubHello(Hello):            # Helloクラスを継承
    def __init__(self, lang, ver):
        super().__init__(lang)    # 親クラスのコンストラクタ
        self.__ver = ver

    def ask(self):
        print(self.__lang + self.__ver + "?")

    def say(self):                # オーバーライド
        print("Hello " + self.__lang + self.__ver + "!")

sub_hello = SubHello("Python", "3")

sub_hello.ask()
# >> Python3?

sub_hello.say()
# >> Hello Python3!
  • 継承元クラスを「親クラス、スーパークラス、基底クラス」、継承した新しいクラスを「子クラス、サブクラス、派生クラス」と呼ぶ
  • super()で親クラスを参照
  • 子クラスでは親クラスと同名のメソッドが再定義でき、子クラスのインスタンスから同名のメソッドを呼び出した場合は、子クラスのメソッドが実行される

プロパティ(ゲッター・セッター・マングリング)

class Code():
    def __init__(self, lang):
        self.__hidden_lang = lang

    @property                # ゲッター
    def lang(self):
        return self.__hidden_lang

    @name.setter             # セッター
    def lang(self, input_lang):
        self.__hidden_lang = input_lang

code = Code("Python")

print(code.lang)             # ゲッター
# >> Python

code.lang = "JavaScript"     # セッター
print(code.lang)
# >> JavaScript

print(code.__hidden_lang)    # マングリング
# >> エラー(※エラー表示は省略)

print(code._Code__hidden_lang)
# >> JavaScript
  • インスタンスプロパティ名の先頭に二つのアンダースコアを付けると、直接アクセスをある程度防ぐことができる

基礎編もあります!
【Python3】他言語エンジニアのためのPythonチートシート《基礎編》

2
5
3

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
2
5