Can @staticmethod's be inherited?
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?
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.
链接地址: http://www.djcxy.com/p/9192.html