Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @staticmethod's be inherited?

Tags:

python

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?

like image 738
alexgolec Avatar asked Feb 20 '11 21:02

alexgolec


People also ask

Can static methods be inherited?

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.

Are Classmethod inherited Python?

Yes, they can be inherited.

Can Staticmethod be inherited Python?

Static method definitions are unchanged even after any inheritance, which means that it can be overridden, similar to other class methods.

Do static members also inherited to sub classes?

Yes, Static members are also inherited to sub classes in java.


2 Answers

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...

like image 162
Mark Tolonen Avatar answered Oct 12 '22 23:10

Mark Tolonen


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.

like image 27
Walter Mundt Avatar answered Oct 12 '22 22:10

Walter Mundt