首頁  >  文章  >  後端開發  >  如何在 Python 中從類別中呼叫類別靜態方法?

如何在 Python 中從類別中呼叫類別靜態方法?

Patricia Arquette
Patricia Arquette原創
2024-10-18 06:47:03250瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn