The question just about says it. I have an abstract class that calls a staticmethod in a helper function, and I want subclasses to simply define the staticmethod and run with it.
Maybe I could use something along the lines of getattr? Should I use a @classmethod instead?
Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic.
Yes, they can be inherited.
Static method definitions are unchanged even after any inheritance, which means that it can be overridden, similar to other class methods.
Yes, Static members are also inherited to sub classes in java.
Something like this:
class A(object):
def func(self):
self.f()
class B(A):
@staticmethod
def f():
print "I'm B"
Testing:
>>> a=x.A()
>>> a.func()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "x.py", line 3, in func
self.f()
AttributeError: 'A' object has no attribute 'f'
>>> b=x.B()
>>> b.func()
I'm B
A
doesn't work on its own and has a helper function that calls a static method. B
defines the static method. This works if I understand what you want correctly...
Yes, it will work, if you use self
to invoke the method, or cls
in a classmethod.
Nonetheless, I'd definitely advise using a classmethod instead. This will allow implentations to look at class attributes, and if you ever end up with multiple levels of inheritance it can make things easier on the intermediate classes to do the right thing.
I have no idea what you're actually doing in your method so it's possible classmethod won't buy you anything in practice. It costs virtually nothing to use though, so you might as well be in the habit of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With