Calling a static method from inside a class

When calling a static method inside a class (which contains a static method), it can be executed as follows:
Class.method () or self.method ()
What is the difference?
What are the unique use cases for each?

class TestStatic(object):
    @staticmethod
    def do_something():
        print 'I am static'

    def use_me(self):
        self.do_something() # 1st way
        TestStatic.do_something() # 2nd way

t = TestStatic()
t.use_me()

prints

I am static
I am static
+4
source share
2 answers

Using TestStatic.do_something(), you will get around any override in the subclass:

class SubclassStatic(TestStatic):
    @staticmethod
    def do_something():
        print 'I am the subclass'

s = SubclassStatic()
s.use_me()

will print

I am the subclass
I am static

This may be what you wanted, or perhaps it is not. Choose the method that best suits your expectations.

+7
source

, TestStatic.do_something() , . - , , , . , .

+1

All Articles