-1

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()
Michael O.
  • 11
  • 5
  • 2
    Why would it be a poor practice? Anyway opinion based questions like these are not a good fit for StackOverflow. – Bakuriu Jul 15 '19 at 19:37
  • The only problem I see with this code is a class method that doesn't actually return an instance of the class; class methods are intended as alternate constructors, and yours doesn't even use `cls`, let alone create an instance of it. – chepner Jul 15 '19 at 19:40
  • Are class methods supposed to always return an instance of the class? In my actual code I have the class method call a static method in the class. I'll update the question – Michael O. Jul 15 '19 at 19:42
  • @MichaelO. No. Class methods are simply methods that need access to the class (in a dynamic way, i.e. if they are called from a derived class they want to know that) to do what they need to do. Now, *usually* (but not always) if you need access to the class is because you have to create at least one instance but it's not written anywhere that one such instance should be returned as a result of the method. Also having access to the class to call other class/static methods is fine. But again, 99% of classmethods will actually return an instance, being outlier is bad code? That's just an opinion – Bakuriu Jul 15 '19 at 19:46

1 Answers1

3

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.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53