1

I am trying different things to understand Decorators and functions in Python. Is the below code correct way :

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()

Will "staticmenthod" decorator tells the built-in default metaclass type (the class of a class, cf. this question) to not create bound methods ? is it possible to do :

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)

Please help me in understanding bound methods and unbound methods and what it the impact of decorator on them.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Nirmal Agarwal
  • 195
  • 2
  • 6

1 Answers1

2

just swap the @staticmethod with your decorator

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 ""

EDIT 1:

python interpreter requires to add @staticmethod at before another decorators, because , before creating a class type ,its need to determines the class members and instance members.if your first decorator is anything else ,interpreter known this function as an instance member. see this

EDIT 2:

it's recommended to use @classmethod instead @staticmethod, for more info see this

Community
  • 1
  • 1
pylover
  • 7,670
  • 8
  • 51
  • 73
  • 2
    An explanation of why this works and OP's code doesn't would be nice. –  Apr 08 '12 at 20:29
  • Thanks for the reply and making me understand . I just have 1 question : does _ in _area() means something specific ? – Nirmal Agarwal Apr 08 '12 at 21:08
  • in python standard naming convention, we add one underscore, to specify protected members, for private members use __(double underscore). – pylover Apr 08 '12 at 21:11