Bagaimana untuk Memanggil Kaedah Statik Kelas dalam Badan Kelas dalam Versi Python <= 3.9?

DDD
Lepaskan: 2024-10-18 06:42:02
asal
585 orang telah melayarinya

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
Salin selepas log masuk

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
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Bagaimana untuk Memanggil Kaedah Statik Kelas dalam Badan Kelas dalam Versi Python <= 3.9?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!