Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling static method from inside the class [closed]

While calling static method from inside the class (which contains the static method), it can be done in following ways:
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
like image 293
rabin utam Avatar asked Jan 22 '15 22:01

rabin utam


2 Answers

By using TestStatic.do_something() you'd bypass any override on a 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 maybe it wasn't. Pick the method that best fits your expectations.

like image 106
Martijn Pieters Avatar answered Oct 03 '22 20:10

Martijn Pieters


I believe that TestStatic.do_something() is better because it demonstrates an understanding of static members. Static members are objects that belong to the class and methods that are called on the class, and in most cases, they are utility classes. Thus, calling the method via the class is more appropriate.

like image 34
Malik Brahimi Avatar answered Oct 03 '22 21:10

Malik Brahimi