Search code examples
pythonclass-method

Is it against pep style rules to call a class method outside of its class?


The code works as intended I was just wondering if it is poor practice to call a class method outside of the class that it was defined in. Example shown below

class A:
      @staticmethod
      def _print_some():
           print("something")

      @classmethod
      def myFunc(cls):
            cls._print_some()

class B:
      def myFunc2(self):
            A.myFunc()

Solution

  • No, that's the point.

    Example:

    import datetime
    ...
    new_date = datetime.datetime.strptime("05/12/2019", "%d/%m/%Y")
    

    The method strptime() is a class method on the class datetime.datetime, which is part of the python stanard library.


    Alternately, the class method can be used outside the class in the very same way as inside the class, in polymorphism. For example, if a method doesn't have any particular state, but its execution is tied to the class that's calling it, which isn't known at runtime.