如何在 Python 版本 <= 3.9 中呼叫類別體內的類別靜態方法?

DDD
發布: 2024-10-18 06:42:02
原創
585 人瀏覽過

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

Python Version <= 3.9: Calling Class Staticmethod Within the Class Body

Problem:

When attempting to call a static method from within the class body using the staticmethod decorator, staticmethod objects are found not to be callable, resulting in a TypeError. This behavior occurs due to descriptor binding.

Workaround:

One workaround is to manually convert the static method into a static method after its last use:

<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
登入後複製

Cleaner Pythonic Method:

For Python versions <= 3.9, one can utilize the __func__ attribute of staticmethod objects to call the raw function:

<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
登入後複製

For Python Versions >= 3.10:

In Python versions 3.10 and above, staticmethod functions can be called directly from within the class scope without any issues.

以上是如何在 Python 版本 <= 3.9 中呼叫類別體內的類別靜態方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!