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

Patricia Arquette
發布: 2024-10-18 06:47:03
原創
244 人瀏覽過

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學習者快速成長!