Python:在调用帮助函数时,动态主张函数的类名称,以插入其DocString

发布于 2025-02-03 16:21:59 字数 761 浏览 1 评论 0 原文

我的设置看起来如下:

def docstring_formatter(func):
    func.__doc__ = func.__doc__.format(class_name=func.__self__.__class__.__name__) #this does not work
    return func

class A:
    @docstring_formatter
    def my_function(self):
        """I am a function of class {class_name}"""
        print("test")

class B(A):
    pass

docstring = getattr(B.my_function, "__doc__")
>>> AttributeError: 'function' object has no attribute '__self__'

我想访问my_function属于的实际类名。由于我使用 help()函数时没有实例化I类,因此 __ self __ __ 属性尚未实例化,我也无法使用 functools.wraps 函数。我想找到一种方法,还可以提取字符串 b b.my_function 当传递时 my_function 可能属于<<对象代码> a()或 b()

I have a setup that looks as following:

def docstring_formatter(func):
    func.__doc__ = func.__doc__.format(class_name=func.__self__.__class__.__name__) #this does not work
    return func

class A:
    @docstring_formatter
    def my_function(self):
        """I am a function of class {class_name}"""
        print("test")

class B(A):
    pass

docstring = getattr(B.my_function, "__doc__")
>>> AttributeError: 'function' object has no attribute '__self__'

I would like to access the actual class name that the instance of my_function belongs to. Since I am not instantiating the class I when I am using the help() function, the __self__ property is not instantiated yet and I can also not make use of the functools.wraps function. I would like to find a way to also extract the string B or B.my_function when being passed a my_function object that could either belong to A() or B().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨落□心尘 2025-02-10 16:21:59

给定代码:

class A:
    def my_function(self):
        print("test")

class B(A):
    pass

b = B()

my_function 对象具有 self 绑定到您从中取的对象,即 b ,因此您可以做:

>>> b.my_function.__name__
'my_function'
>>> b.my_function.__self__.__class__.__name__
'B'

Given the code:

class A:
    def my_function(self):
        print("test")

class B(A):
    pass

b = B()

The my_function object has a self binding to the object you took it from, which is a B, so you can do:

>>> b.my_function.__name__
'my_function'
>>> b.my_function.__self__.__class__.__name__
'B'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文