Skip to content

Python覚書

HIRO edited this page Jun 30, 2023 · 15 revisions

命名規則

名前をつけるもの 命名規則
変数 スネークケース variable_name
定数 全部大文字のスネークケース CONSTANT_NAME
グローバル変数 スネークケース global_variable_name
関数 スネークケース function_name
関数の引数 スネークケース function_parameter_name
クラス パスカルケース ClassName
インスタンス変数 スネークケース instance_variable_name
メソッド スネークケース method_name
パッケージ スネークケース package_name
モジュール スネークケース module_name

出典: https://python.softmoco.com/basics/python-naming-conventions.php

インデント

他言語と異なり、インデントの深さでブロックが決まることに注意。
多くのライブラリで空白スペース4つとなっている。
決まりはなく、プロジェクト内で統一されていれば良い。

コメントアウト

行中 # 以降はコメント扱いになる。

クラス

# 通常のクラス
class MyClass:
    # static属性
    staticValue = "static"

    # コンストラクタ
    __init__(self):
        # インスタンス属性
        self.name = ""
        self.lang = "ja"
    
    # staticメソッド
    @staticmethod
    def static_do():
        print(MyClass.staticValue)

    # インスタンスメソッド
    def do(self):
        print(self.name)

# 派生クラス
class Parent:
    # 内容が存在しない場合は pass でブロックを閉じる
    pass

class Child(Parent):
    pass

インターフェース

# インターフェースを定義するために ABC を利用する
from abc import ABC

# インターフェース
class IMyClass(ABC):
    # 抽象クラス
    @abstractmethod
    def abstract_do(self):
        pass

# 具象クラス
class MyClass(IMyClass):
    __init__(self):
        pass

    # 抽象メソッドの実装
    abstract_do(self):
        pass

for~in

要素数だけ繰り返す処理。

for item in items:
    print(item.value)

List => String

print(list)
# ['A', 'B', 'C']

print(" ".join(list))
# [A B C]

try-except

try-catchに該当する構文。
excepttryの中で例外が起きた場合に、
elsetryの中で例外が起きなかった場合に実行される。

except (例外クラス) as (変数名): で、例外の内容を捕捉できる。

try:
    value1 = 0
    value2 = 1
    
    print(value2 / value1)
except Exception as e:
    print(e)
else:
    print("No Error!")
finally:
    print("Done!")

出力例

division by zero
Done!

型判定

type(判定対象) で型を取得できる。

def is_str(v):
    return type(v) is str # 複数の型を判定したい場合は、in (Class1, Class2) とする

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False

instance(比較対象, クラス)は比較対象が派生クラスのオブジェクトでも一致とみなす。

print(type(True))
# <class 'bool'>

print(type(True) is bool)
# True

print(type(True) is int)
# False

print(isinstance(True, bool))
# True

# Pythonの bool は int の派生クラス
print(isinstance(True, int))
# True

## match-case文

他言語のswitch-case文に該当するが、様々なバリエーションがある。
参考:https://www.lifewithpython.com/2021/06/python-structual-pattern-matching.html

Clone this wiki locally