Toby Petty
Toby Petty

Reputation: 4660

Correct/preferred way to access staticmethod from within class instance

When accessing a static method from a regular instance method in a Python class, there are 2 different options which both seem to work - accessing via the self object, and accessing via the class name itself, e.g.

class Foo:

    def __init__(self, x: int):
        self.x = x

    @staticmethod
    def div_2(x: int):
        return x / 2

    def option_1(self):
        return Foo.div_2(self.x)

    def option_2(self):
        return self.div_2(self.x)

Is there any reason for preferring one way over the other?

Upvotes: 1

Views: 46

Answers (1)

6502
6502

Reputation: 114461

The two do different things: Foo.div_2 calls the method of Foo; instead self.div_2 may call a different method if self if an instance of a class derived from Foo:

class Bar(Foo):
    @staticmethod
    def div_2(x: int):
        return x * 2

b = Bar(12)
print(b.option_1()) # prints 6.0
print(b.option_2()) # prints 24

Upvotes: 3

Related Questions