いろは3011036 views
高校化学2924523 views
高校日本史190578 views
中学社会668782 views
高校生物551780 views
高校物理160216 views
中学数学623778 views
高校倫理1440172 views
中学英語811754 views
小学算数1200472 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesLanguage Model NewsSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksCherry BlossomWater RippleWater SplashBreaking GlassGlass TextureFabric TextureWood GrainMarble TextureBrick Wall TextureMetal TextureWashi Paper TextureCardboard TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsRolling DiceCross SectionsMotion PathMechanicsWavesElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

Python デコレータの仕組みと自作方法

デコレータは関数を受け取り、新しい関数を返す仕組みです。既存の関数に機能を追加したいとき、元のコードを変更せずに拡張できます。

デコレータの基本構造

デコレータは「関数を引数に取り、関数を返す関数」です。

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("関数実行前")
        result = func(*args, **kwargs)
        print("関数実行後")
        return result
    return wrapper

この my_decorator を使うには、@ 記法を使います。

@my_decorator
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

実行結果は以下のようになります。

関数実行前
Hello, Alice!
関数実行後

@ 記法は糖衣構文であり、greet = my_decorator(greet) と同じ意味です。

実用的なデコレータの例

実行時間を計測するデコレータを作ってみましょう。

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"{func.__name__} の実行時間: {end - start:.4f}秒")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "完了"

デコレータを使うことで、計測ロジックを関数本体から分離できます。ログ出力、認証チェック、キャッシュなど、横断的な関心事を扱うのに適しています。