by shigemk2

当面は技術的なことしか書かない

デコレータ 継承

pythonに不馴れで、しかもデコレータと継承の違いがよくわからなかったので。

デコレータ
Python - デコレータ

デコレータは、デコレートする関数定義の手前で前もって関数を置き換える

デコレータと継承
classmethodとstaticmethodデコレータの違い - SELECT * FROM life;

Pythonでstaticなメソッドを定義しようとする場合、staticmethodデコレータかclassmethodデコレータを使うことになります。これらの違いは、classmethodデコレータでは第一引数がクラスそのものになるのに対し、staticmethodでは特にそういった制約がない、ということです。この違いが意味を持つのは、クラスの継承が行われた場合

def deco(func):
    print("deco")
    return "string"
@deco
def test():
    pass

class Hoge(object):
    name = 'hoge'
    def fuga(func):
        print('fuga')

    @fuga
    def test1():
        pass

    @staticmethod
    def static_method():
        print Hoge.name

    @classmethod
    def class_method(cls):
        print cls.name

Hoge.static_method()
Hoge.class_method()

class HogeHoge(Hoge):
   name = 'hogehoge'

HogeHoge.static_method()
HogeHoge.class_method()

結果

deco
fuga
hoge
hoge
hoge
hogehoge