如何在 Python 中从类体内调用类静态方法?

Patricia Arquette
发布: 2024-10-18 06:47:03
原创
245 人浏览过

How to Call Class Static Methods from within the Class Body in Python?

在 Python 中的类体内调用类静态方法

对于 Python 版本 3.10 及更高版本,从类体内调用静态方法非常简单。但是,对于 3.9 及更早版本,这提出了挑战。

遇到错误

尝试从类主体内调用静态方法时,可能会遇到以下错误:

TypeError: 'staticmethod' object is not callable
登录后复制

发生此错误是因为静态方法在使用 staticmethod 装饰器声明时成为描述符。描述符绑定到类而不是实例,使得它们无法从类体内访问。

使用 __func__ 属性的解决方法

一种解决方法是通过 __func__ 属性访问原始函数静态方法对象:

<code class="python">class Klass(object):

    @staticmethod
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret</code>
登录后复制

附加说明

  • 虽然上述解决方法有效,但 __func__ 属性是一个实现细节,可能会在未来的 Python 版本中更改。
  • 对于 Python 3.10 及更高版本,从类体内调用静态方法非常简单,如下所示:
<code class="python">class Klass(object):

    @staticmethod
    def stat_func():
        return 42

    def method(self):
        ret = Klass.stat_func()
        return ret</code>
登录后复制

以上是如何在 Python 中从类体内调用类静态方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!