Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 How to use factory pattern?
#1
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.
Quote
#2
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.
bhojendra likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#3
Ah, I was just missing self. Thanks.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Factory Design Pattern Prince 1 587 Apr-06-2018, 10:00 AM
Last Post: Larz60+

Forum Jump:


Users browsing this thread: 1 Guest(s)