Reputation: 497
I have some methods, which I want to use outside of a class directly and as well group them inside some different classes.
How to define a method outside of the class definition is already properly answered:
However, I found nothing about static methods.
What is the best way to do it?
For a class like:
class some_class:
@staticmethod
def some_haevy_method(...):
...
I tried the following:
def some_haevy_method(...):
...
class some_class:
@staticmethod
some_haevy_method = some_haevy_method
Doesn't compile: SyntaxError: invalid syntax
def some_haevy_method(...):
...
class some_class:
@staticmethod
def some_haevy_method(...):
pass
some_haevy_method = some_haevy_method
Error: some_haevy_method () takes 0 positional arguments but 1 was given
(decorator is overwritten, self is passed)
def some_haevy_method(...):
...
class some_class:
@staticmethod
def some_haevy_method(*args, **kwargs):
return some_haevy_method(*args, **kwargs)
This actually works, but the drawback is, that the documentation and type hinting is not available.
Edit: Since it was asked in comments.
I want to use my some_haevy_method
directly in scripts without even knowing about the class.
Also it will appear in some classes. And this classes have children and the children have other children. And every of them should be able to provide this functionality.
Probably it is a little lazy coding, since my classes are in this example more thematic grouped methods but it helps me in my project. For example when I am debugging, and I don't have to load the specific methods every time.
Feel free to roast me in the comments :)
Upvotes: 1
Views: 347
Reputation: 530940
Decorator syntax is only used for function and class definitions, but is only necessary in those cases to avoid repetition of names. The syntax is just a shortcut for assignments, so you can write
def some_heavy_method(...):
...
class some_class:
some_heavy_method = staticmethod(some_heavy_method
The decorator syntax is always just a convenience; without it, you could always simply write
class some_class:
def f():
...
f = staticmethod(f)
Upvotes: 2