いろは3010814 views
高校日本史190571 views
数学講師2886227 views
LaTeX962153 views
中学英語811710 views
中学理科1630641 views
中学社会668760 views
雑学1473612 views
ヒストリア290598 views
英語613639 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble 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 の関数オブジェクトの属性(__name__, __annotations__ など)

Python の関数はオブジェクトであり、さまざまな属性を持っています。これらの属性を理解すると、デバッグやメタプログラミングに役立ちます。

主要な属性

def greet(name: str, greeting: str = "Hello") -> str:
    """挨拶を返す関数"""
    return f"{greeting}, {name}!"

この関数の属性を確認してみましょう。

__name__関数名("greet")
__doc__docstring("挨拶を返す関数")
__module__定義されたモジュール名
__qualname__修飾名(クラス内なら "Class.method")
__annotations__型アノテーションの辞書
__defaults__デフォルト引数のタプル
__kwdefaults__キーワード専用引数のデフォルト
__code__コードオブジェクト
__globals__グローバル名前空間への参照
__dict__関数に付加された属性

属性の取得例

print(greet.__name__)         # greet
print(greet.__doc__)          # 挨拶を返す関数
print(greet.__annotations__)  # {'name': <class 'str'>, ...}
print(greet.__defaults__)     # ('Hello',)

code オブジェクト

コードオブジェクトには詳細な情報が含まれます。

code = greet.__code__
print(code.co_varnames)   # ('name', 'greeting')
print(code.co_argcount)   # 2
print(code.co_filename)   # ファイル名
print(code.co_firstlineno) # 定義開始行

関数に属性を追加

関数もオブジェクトなので、任意の属性を追加できます。

def counter():
    counter.count += 1
    return counter.count

counter.count = 0
print(counter())  # 1
print(counter())  # 2

関数の属性を活用すると、関数の内部構造を調べたり、動的な処理を実装したりできます。