
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:
1 | TypeError: 'staticmethod' object is not callable
|
Copier après la connexion
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:
1 2 3 4 5 6 7 8 9 10 11 | <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>
|
Copier après la connexion
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:
1 2 3 4 5 6 7 8 9 | <code class = "python" > class Klass(object):
@staticmethod
def stat_func():
return 42
def method(self):
ret = Klass.stat_func()
return ret</code>
|
Copier après la connexion
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!