代码之家  ›  专栏  ›  技术社区  ›  cardamom

python函数似乎调用自己然后点[复制]

  •  1
  • cardamom  · 技术社区  · 6 年前

    没有多少人知道这个特性,但是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将语法规则与方法关联。但是自定义属性呢?有充分的理由使用它们吗?

    0 回复  |  直到 16 年前