0

I have a class whose existence - or not - depends on the correctness of some input parameters.

QUESTION:
Would it be ok to create that factory function as a static member of the class I want an instance of? Is that the best way?

I initially tried to do it inside the __new__ operator but people said I should use factory function.

class MyClass:
    @staticmethod
    def GetAMy(arg):
        if arg == 5:
            return None
        else:
            return MyClass(arg)
Bob
  • 4,576
  • 7
  • 39
  • 107
  • 2
    So what's the question? And why not make it a `@classmethod` instead, so you can use `def GetAMy(cls, arg):` and `return cls(arg)`? – Martijn Pieters Jul 29 '16 at 21:32
  • @MartijnPieters I'm not familiar with `@classmethod`; I'll look it up. I bolded the question – Bob Jul 29 '16 at 21:33
  • 1
    You can do it with `__new__`, see [using class new method as a factory](http://stackoverflow.com/questions/5953759/using-a-class-new-method-as-a-factory-init-gets-called-twice) – Chris Jul 29 '16 at 23:04
  • @Chris yes that was my intention. But I've been traumatized by the horrible non-documentation of `super()` – Bob Jul 30 '16 at 19:35

2 Answers2

0

An alternative to using @classmethod would be to put the factory function in the same file as the class.

myclasses.py

def GetAMy(arg):
    if arg == 5:
        return None
    else:
        return MyClass(arg)

class MyClass(object):
    ...

You then import the module from your main file:

import myclasses
a=myclasses.GetAMy(5)
Munchhausen
  • 442
  • 4
  • 16
  • I know that would work but I'm thinking since they're so linked, I'd put the factory function inside the main class. My question was more like "will this result in bad issues down the road". – Bob Jul 29 '16 at 21:47
  • 1
    Ah okay. Is your class going to be subclassed somewhere? classmethod has the advantage of being inherited. staticmethod does not get inherited. Here is some information on a comparison between the two: http://stackoverflow.com/a/12179752/6647217 – Munchhausen Jul 29 '16 at 22:14
-2

A Simple Factory in Python:

import sys

class Usecase:
    @staticmethod
    def getClassFromStr(usecase):
        return getattr(sys.modules[__name__], usecase)

    @classmethod
    def getUsecase(cls, usecase):
      try:
        if issubclass(Usecase.getClassFromStr(usecase), Usecase):
            return Usecase.getClassFromStr(usecase)()
        else:
            print("Not a valid usecase")
            return None
      except AttributeError:
        print("Not a valid class")
        return None

class AllStops(Usecase):
    def __init__(self):
       print("AllStops")


class StopDetails(Usecase):
    def __init__(self):
       print("StopDetails")

class Other:
    def __init__(self):
       print("Other")



if __name__ ==  '__main__':
    a = Usecase.getUsecase("AllStops")
    b = Usecase.getUsecase("StopDetails")
    c = Usecase.getUsecase("ABC")
    d = Usecase.getUsecase("Other")