Python Forum
How to use factory pattern? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to use factory pattern? (/thread-17921.html)



How to use factory pattern? - bhojendra - Apr-29-2019

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.


RE: How to use factory pattern? - ichabod801 - Apr-29-2019

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.


RE: How to use factory pattern? - bhojendra - Apr-29-2019

Ah, I was just missing self. Thanks.