Discuss / Python / 一个装饰器的例子

一个装饰器的例子

Topic source

抑郁胖子

#1 Created at ... [Delete] [Delete and Lock User]

网上看到的例子,simple_areas函数实现了三种形状的求面积,支持不定参数:如果传进一个参数就以其作为直径求圆面积;两个参数则为矩形两边;三个参数则为三角形三边:

def simple_areas(*args):
    import math
    areas = []
    def half(x):
        return x / 2
    @areas.append
    def circle(diameter):
        radius = half(diameter)
        return radius ** 2 * math.pi
    @areas.append
    def rectangle(width, height):
        return width * height
    @areas.append
    def triangle(a, b, c):
        """Heron's formula"""
        perimeter = a + b + c
        s = half(perimeter)
        return math.sqrt(s*(s - a)*(s - b)*(s - c))
    for area in areas:
        try:
            return area(*args)
        except TypeError:
            continue

充分说明了装饰器的特性,实际上"Decorators can be any callables that accept one argument that is a function (or class)":

@id
class Student(object):
    pass

>>> Student
22103480

  • 1

Reply