Search code examples
pythonstatic-methods

Maintaining staticmethod calls if class is renamed


I have a class with a static method which is called multiple times by other methods. For example:

class A:
    def __init__(self):
        return

    @staticmethod
    def one():
        return 1

    def two(self):
        return 2 * A.one()

    def three(self):
        return 3 * A.one()

Method one is a utility function that belongs inside the class but isn't logically an attribute of the class or the class instance.

If the name of the class were to be changed from A to B, do I have to explicitly change every call to method one from A.one() to B.one()? Is there a better way of doing this?


Solution

  • I pondered this question once upon a time and, while I agree that using a refactoring utility is probably the best way to go, as far as I can tell it is technically possible to achieve this behaviour in two ways:

    1. Declare the method a classmethod.
    2. Use the __class__ attribute. Leads to rather messy code, and may well be deemed unsafe or inefficient for reasons I am not aware of(?).

      class A:
          def __init__(self):
              return
      
          @staticmethod
          def one():
              return 1
      
          @classmethod
          def two(cls):
              return 2 * cls.one()
      
          def three(self):
              return 3 * self.__class__.one()
      
      a = A()
      print(a.two())
      print(a.three())