How to Call Class Static Methods from within the Class Body in Python?

Patricia Arquette
Release: 2024-10-18 06:47:03
Original
245 people have browsed it

How to Call Class Static Methods from within the Class Body in Python?

Calling Class Staticmethod within the Class Body in Python

For Python versions 3.10 and above, calling a static method from within the class body is straightforward. However, for versions 3.9 and earlier, this poses a challenge.

Error Encountered

When attempting to call a static method from within the class body, you may encounter the following error:

TypeError: 'staticmethod' object is not callable
Copy after login

This error occurs because static methods, when declared using the staticmethod decorator, become descriptors. Descriptors bind to the class instead of the instance, making them inaccessible from within the class body.

Workaround Using __func__ Attribute

One workaround is to access the original raw function through the __func__ attribute of the static method object:

<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>
Copy after login

Additional Notes

  • While the above workaround is functional, the __func__ attribute is an implementation detail and may change in future Python versions.
  • For Python versions 3.10 and above, calling static methods from within the class body is straightforward as shown below:
<code class="python">class Klass(object):

    @staticmethod
    def stat_func():
        return 42

    def method(self):
        ret = Klass.stat_func()
        return ret</code>
Copy after login

The above is the detailed content of How to Call Class Static Methods from within the Class Body in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!