Python Forum

Full Version: How to use factory pattern?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to understand and use factory pattern like:

class Factory():
  @staticmethod
  def getObj():
    return Drive()
    
class Drive():
  def select():
    print('select method from Drive class called')

obj = Factory.getObj()
obj.select()
But it throws an error:

Error:
TypeError: select() takes 0 positional arguments but 1 was given
Please help me understanding and using factory pattern.
Methods are typically bound methods: they are bound to a specific instance. That instance is provided automatically to the method as it's first parameter. The convention is to call that parameter self.

So obj is an instance of Drive. When you call select, obj is given as the first parameter, without you having to specify it. But your def statement on line 7 doesn't define that parameter. So you need to change line 7 to def select(self):. Note that this isn't a problem with getObj, since you decorated that as a static method, which doesn't use the self parameter.
Ah, I was just missing self. Thanks.