我正在尝试编写一个装饰器来做日志记录:
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
Run Code Online (Sandbox Code Playgroud)
我想要打印:
Entering C.f
Run Code Online (Sandbox Code Playgroud)
但我收到此错误消息:
AttributeError: 'function' object has no attribute 'im_class'
Run Code Online (Sandbox Code Playgroud)
据推测,这与'logger'中'myFunc'的范围有关,但我不知道是什么.
编辑: 截至目前(Sphinx 1.4.9)似乎没有办法告诉Sphinx做我想做的事(参见GitHub上的问题).该接受的答案,从布莱希特Machiels解决以其他方式问题,直到狮身人面像可能是能够做到一天.
描述:
我正在尝试使用sphinx-apidoc记录Python项目.Sphinx配置几乎是默认的,我只是包括在内'sphinx.ext.autodoc'.
它一般工作,但派生类不会像我期望的那样继承其超类的方法文档.
示例:
考虑一个非常简约的Python包project.除了空__init__.py,它只包含一个文件(base.py见下文)
# -*- coding: utf-8 -*
import abc
class Superclass(object):
"""The one to rule them all"""
@abc.abstractmethod
def give(self, ring):
"""Give out a ring"""
pass
class Derived(Superclass):
"""Somebody has to do the work"""
def give(self, ring):
print("I pass the ring {} to you".format(ring))
Run Code Online (Sandbox Code Playgroud)
运行sphinx-apidoc(sphinx-apidoc -o apidoc project -f)会生成以下文件:
apidoc/modules.rst
project
=======
.. toctree::
:maxdepth: 4
project
Run Code Online (Sandbox Code Playgroud)apidoc/project.rst
project package …Run Code Online (Sandbox Code Playgroud)我有一些相互继承的类。所有类都包含相同的方法(让我们称之为mymethod),由此子类覆盖基类方法。我想mymethod使用sphinx为所有类生成文档。
假设mymethod接受一个论点myargument。此参数对于基方法和继承方法具有相同的类型和含义。为了尽量减少冗余,我myargument只想为基类编写文档,并将文档插入子方法的文档中。也就是说,我不想只对基类进行简单的引用,而是在生成文档时动态插入文本。
这能做到吗?如何?
请在下面找到一些说明问题的代码。
class BaseClass
def mymethod(myargument):
"""This does something
Params
------
myargument : int
Description of the argument
"""
[...]
class MyClass1(BaseClass):
def mymethod(myargument):
"""This does something
Params
------
[here I would like to insert in the description of ``myargument`` from ``BaseClass.mymethod``]
"""
BaseClass.mymethod(myargument)
[...]
class MyClass2(BaseClass):
def mymethod(myargument, argument2):
"""This does something
Params
------
[here I would like to insert in …Run Code Online (Sandbox Code Playgroud) 我想以设置func_doc(作为表达)内 def.
def f():
'''My function help''' #Set the docstring
def g():
"My function " + "help" # An expression, so not read as a docstring
# can I put something here to set the docstring as an expression?
g.func_doc # is None
g.func_doc = "My function " + "help" # This works
Run Code Online (Sandbox Code Playgroud)
这可能吗?
(我可以考虑这样做的两个原因:从模块导入函数(并且您也想导入文档字符串)和使用词法分析器.)