4

I have written a code like this,and they are all works for me,but what is the difference? which is better?

class Demo1(object):
    def __init__(self):
        self.attr = self._make_attr()
    def _make_attr(self):
        #skip...
        return attr

class Demo2(object):
    def __init__(self):
        self.attr = self._make_attr()
    @staticmethod
    def _make_attr():
        #skip...
        return attr
PyChan
  • 41
  • 1
  • 1

3 Answers3

1

If both are working it means that inside make_attr you are not using self.

Making it a regular non-static method only makes sense if the code could logically depend on the instance and only incidentally doesn't depend on it in the current implementation (but for example it could depend on the instance in a class derived from this class).

6502
  • 112,025
  • 15
  • 165
  • 265
  • Since it's called as `self._make_attr`, a subclass could in effect override the staticmethod in `Demo2` in the same way it can actually override the normal method in `Demo1`. You're probably correct, though, that it makes more sense to indicate in the base class whether or not this is expected. As another matter of coding style, it's in any case probably a mistake to name a function with an initial underscore if it's expected to be overridden in derived classes, but that's a matter of conventions for a project/team. – Steve Jessop Oct 06 '13 at 19:03
0

When it comes to functionality, @staticmethod doesn't really matter. It's value is semantic - you are telling yourself, or other coders, that even though this function belongs to the namespace of the class, it isn't tied to any specific instance. This kind of tagging can be very useful when refactoring the code or when looking for bugs.

Erez
  • 1,287
  • 12
  • 18
0

In either, attr is a local variable and does not depend on anything in the class. The results are the same. Marking it as static gives you the benefit of knowing this, and being able to access it directly, such as Demo2._make_attr() without having to create and instance of the class.

If you want it to acces the class variable, you would reference it as self.attr. But if you're doing this, then Demo2._make_attr() can no longer be static.

Adam Morris
  • 8,265
  • 12
  • 45
  • 68