1

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?

1
  • The way I do this is to use self.div_2 from within another method and Foo.div_2 from outside the class. Commented Nov 25, 2019 at 21:45

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that's an interesting consideration I hadn't thought of.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.