0

Following this tutorial I'm trying to use Abstract Base Classes in Python. So I constructed two files:

basis.py:

import abc

class PluginBase(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def load(self, input):
        return

and implementation.py:

import abc
from basis import PluginBase

class SubclassImplementation(PluginBase):

    def load(self, input):
        print input
        return input

if __name__ == '__main__':
    print 'Subclass:', issubclass(SubclassImplementation, PluginBase)
    print 'Instance:', isinstance(SubclassImplementation(), PluginBase)

running python implementation.py works fine, but I now want to use implementation.py as a module for something else. So I get into the command line and do:

>>> from implementation import SubclassImplementation as imp
>>> imp.load('lala')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method load() must be called with SubclassImplementation instance as first argument (got str instance instead)
>>>

What am I doing wrong here, and how can I make this work? All tips are welcome!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

3

You do need to create an instance:

from implementation import SubclassImplementation as imp

imp().load('lala')

This is not a specific ABC problem either; this applies to all Python classes and methods, unless you make SubclassImplementation.load a classmethod.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • As I said to Daniel as well, I've been working way to much with php static functions lately (bLuh, I love Python!) that I totally forgot this. Thanks anyway! – kramer65 Mar 12 '14 at 13:29
3

This doesn't have anything to do with ABCs.

The object you've called imp is a class, ie SubclassImplementation. You'll need to instantiate it before you can call any of its instance methods. Alternatively, you could make load a classmethod.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • How stupid of me. I have been working a lot with Static functions in php lately, so I got so used to directly running functions from a class, that I just forgot about instances. Thanks anyway! – kramer65 Mar 12 '14 at 13:28