1

Python のデコレータと関数を理解するために、さまざまなことを試みています。以下のコードは正しい方法ですか:

import math
def calculate_area(func):
    def area(a,b):
        return a+b
    return area

class Donut():
    def __init__(self, outer, inner):
        self.inner = inner
        self.outer = outer

    @calculate_area
    @staticmethod
    def area(self):
        outer, inner = self.radius, self.inner
        return Circle(outer).area() - Circle(inner).area()

「staticmenthod」デコレーターは、組み込みのデフォルトのメタクラス タイプ (クラスのクラス、この質問を参照) に、バインドされたメソッドを作成しないように指示しますか? することは可能ですか:

Donut.area(4,5)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
Donut.area(4,5)
TypeError: unbound method area() must be called with Donut instance as first argument      (got int instance instead)

バインドされたメソッドとバインドされていないメソッド、およびデコレータがそれらに与える影響を理解するのを手伝ってください。

4

1 に答える 1

2

@staticmethod をデコレータと交換するだけです

import math
def calculate_area(func):
    def _area(a, b):
        return a + b
    return _area

class Donut():
    def __init__(self, outer, inner):
        self.inner = inner
        self.outer = outer

    @staticmethod
    @calculate_area
    def area(cls):
        outer, inner = self.radius, self.inner
        return ""

編集1:

Python インタープリターは、別のデコレーターの前に @staticmethod を追加する必要があります。これは、クラス タイプを作成する前に、クラス メンバーとインスタンス メンバーを決定する必要があるためです。最初のデコレーターがそれ以外の場合、インタープリターはこの関数をインスタンス メンバーとして認識します。これを見る

編集2:

@staticmethod の代わりに @classmethod を使用することをお勧めします。詳細については、こちらを参照してください

于 2012-04-08T20:03:20.953 に答える