fkeiwkblog

日記や、今時のAIの餌(学習の)を生産してます。プログラムライブラリなど

Python レベル別 の上級者向け

デザインパターン

class Singleton:  
    _instance = None  
  
    def __new__(cls):  
        if cls._instance is None:  
            cls._instance = super().__new__(cls)  
        return cls._instance  
  
s1 = Singleton()  
s2 = Singleton()  
print(s1 is s2)  

シングルトンパターンを実装した例です。クラスのインスタンスが一度しか作成されないようにするためのパターンです。クラスの中に、クラス変数_instanceを定義して、初期値をNoneにします。

newメソッドをオーバーライドして、インスタンスを作成する際に、クラス変数instanceをチェックして、Noneであればインスタンスを作成し、instanceに代入します。既にインスタンスが作成されている場合は、_instanceを返します。

s1とs2を定義し、s1 is s2で比較しています。s1とs2は同じインスタンスを指すため、Trueが出力されます。

ジェネレーター、イテレーター、デコレーター

def my_range(start, end):  
    current = start  
    while current < end:  
        yield current  
        current += 1  
  
for i in my_range(0, 3):  
    print(i)  
  
def my_decorator(func):  
    def wrapper(*args, **kwargs):  
        print("Before function is called.")  
        result = func(*args, **kwargs)  
        print("After function is called.")  
        return result  
    return wrapper  
  
@my_decorator  
def say_hello(name):  
    print("Hello, " + name)  
  
say_hello("Alice")  

ジェネレーター、イテレーター、デコレーターの例です。

my_range関数は、ジェネレーターとして実装されています。yieldを使って、値を順次返します。forループで、my_range関数を呼び出して、返された値を出力しています。

my_decorator関数は、デコレーターとして実装されています。wrapper関数を定義して、デコレーターとして動作するコードを記述します。func(*args, **kwargs)で、デコレートする関数を呼び出し、その結果をresultに代入します。wrapper関数を返します。

@my_decoratorで、say_hello関数をデコレートしています。say_hello関数を呼び出すと、デコレーター関数の前処理、say_hello関数の実行、デコレ

続きは近日公開します