Python函数属性 - 使用和滥用

时间:2008-12-03 17:56:45

标签: python function attributes

没有多少人知道这个功能,但Python的功能(和方法)可以有attributes。看哪:

>>> def foo(x):
...     pass
...     
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score']
>>> foo.score
10
>>> foo.score += 1
>>> foo.score
11

Python中此功能的可能用途和滥用情况是什么?我知道的一个很好的用途是PLY使用docstring将语法规则与方法相关联。但是自定义属性呢?有充分的理由使用它们吗?

8 个答案:

答案 0 :(得分:140)

我通常使用函数属性作为注释的存储。假设我想以C#的方式编写(表明某个方法应该是Web服务接口的一部分)

class Foo(WebService):
    @webmethod
    def bar(self, arg1, arg2):
         ...

然后我可以定义

def webmethod(func):
    func.is_webmethod = True
    return func

然后,当webservice调用到达时,我查找方法,检查底层函数是否具有is_webmethod属性(实际值是无关紧要的),如果方法不存在或者不打算调用,则拒绝服务网络。

答案 1 :(得分:115)

我已将它们用作函数的静态变量。例如,给出以下C代码:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

我可以在Python中类似地实现该功能:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

这绝对属于频谱的“滥用”。

答案 2 :(得分:49)

你可以用JavaScript方式做对象......没有意义,但它有效;)

>>> def FakeObject():
...   def test():
...     print "foo"
...   FakeObject.test = test
...   return FakeObject
>>> x = FakeObject()
>>> x.test()
foo

答案 3 :(得分:14)

我谨慎使用它们,但它们非常方便:

def log(msg):
   log.logfile.write(msg)

现在我可以在整个模块中使用log,只需设置log.logfile即可重定向输出。有很多其他方法可以实现这一点,但这个轻量级,简单易用。虽然我第一次这样做时闻起来很有趣,但我开始相信它比拥有全局logfile变量更好闻。

答案 4 :(得分:10)

函数属性可用于编写轻量级闭包,将代码和相关数据包装在一起:

#!/usr/bin/env python

SW_DELTA = 0
SW_MARK  = 1
SW_BASE  = 2

def stopwatch():
   import time

   def _sw( action = SW_DELTA ):

      if action == SW_DELTA:
         return time.time() - _sw._time

      elif action == SW_MARK:
         _sw._time = time.time()
         return _sw._time

      elif action == SW_BASE:
         return _sw._time

      else:
         raise NotImplementedError

   _sw._time = time.time() # time of creation

   return _sw

# test code
sw=stopwatch()
sw2=stopwatch()
import os
os.system("sleep 1")
print sw() # defaults to "SW_DELTA"
sw( SW_MARK )
os.system("sleep 2")
print sw()
print sw2()

1.00934004784

2.00644397736

3.01593494415

答案 5 :(得分:3)

有时我使用函数的属性来缓存已计算的值。您还可以使用通用装饰器来概括此方法。注意并发问题和这些功能的副作用!

答案 6 :(得分:2)

我已经创建了这个辅助装饰器来轻松设置功能属性:

def with_attrs(**func_attrs):
    """Set attributes in the decorated function, at definition time.
    Only accepts keyword arguments.
    E.g.:
        @with_attrs(counter=0, something='boing')
        def count_it():
            count_it.counter += 1
        print count_it.counter
        print count_it.something
        # Out:
        # >>> 0
        # >>> 'boing'
    """
    def attr_decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            return fn(*args, **kwargs)

        for attr, value in func_attrs.iteritems():
            setattr(wrapper, attr, value)

        return wrapper

    return attr_decorator

用例是创建工厂集合并查询它们可以在函数元级别创建的数据类型 例如(非常愚蠢):

@with_attrs(datatype=list)
def factory1():
    return [1, 2, 3]

@with_attrs(datatype=SomeClass)
def factory2():
    return SomeClass()

factories = [factory1, factory2]

def create(datatype):
    for f in factories:
        if f.datatype == datatype:
            return f()
    return None

答案 7 :(得分:1)

我总是假设这是可能的唯一原因是因此有一个合理的位置来放置文档字符串或其他类似的东西。我知道如果我将它用于任何生产代码,它会让大多数读者感到困惑。