rdp
rdp

Reputation: 2088

Is it a good idea to call a staticmethod in python on self rather than the classname itself

If I have the following class.

class Foo:
    @staticmethod
    def _bar():
        # do something
        print "static method"

    def instancemethod(self):
        Foo._bar()  # method 1
        self._bar() # method 2

In this case, is method 1 a preferred way of calling staticmethod _bar() or method 2 in the Python world?

Upvotes: 4

Views: 95

Answers (1)

user2357112
user2357112

Reputation: 280708

Write the code that expresses what you want to do. If you want to call this method right here:

class Foo:
    @staticmethod
    def _bar():  # <-- this one
        # do something
        print "static method"

then specify that particular method:

Foo._bar()

If you want to call whatever self._bar resolves to, meaning you've actually decided that it makes sense to override it and made sure your code still behaves sensibly when that method is overridden, then specify self._bar:

self._bar()

Most likely, this method isn't designed to be overridden, and the code that uses it isn't designed to anticipate overriding it, so you probably want Foo._bar().

Upvotes: 5

Related Questions