如何在 Python 版本 <= 3.9 中调用类体内的类静态方法?

DDD
发布: 2024-10-18 06:42:02
原创
584 人浏览过

How to Call Class Staticmethods within the Class Body in Python Versions <= 3.9?

Python 版本

问题:

当尝试使用 staticmethod 装饰器从类体内调用静态方法时,发现 staticmethod 对象不可调用,从而导致 TypeError。此行为是由于描述符绑定而发生的。

解决方法:

一种解决方法是在静态方法最后一次使用后手动将其转换为静态方法:

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

    def _stat_func():
        return 42

    _ANS = _stat_func()  # Use the non-staticmethod version

    _stat_func = staticmethod(_stat_func)  # Convert function to a static method

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

更简洁的 Pythonic 方法:

对于 Python 版本

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

    @staticmethod  # Use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # Call the staticmethod

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

对于 Python 版本 >= 3.10:

在 Python 3.10 及更高版本中,可以直接从类作用域内调用 staticmethod 函数,不会出现任何问题。

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

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