Mtl Dev
Mtl Dev

Reputation: 1622

Learning Python: implementing a virtual method

First day learning Python, please excuse the basic question.

Assuming I have been given an object which contains an unimplemented method that I need to implement, e.g:

class myclass():
  def __init__(self)
    self.unimplementedmethod = False

What is the correct way to implement this in an instantiated object? I do not want to alter the base class in any way. I have experimented and found the following code seems to work, but is it correct/good style?

def methodimplementation():
  print("method called")

myobject = myclass()
myobject.unimplementedmethod=methodimplementation

Is this the right path? Or should I be doing something different like perhaps creating a derived class first, implementing the methods in it, and then instantiating an object based on the derived class? What is best practice?

Upvotes: 0

Views: 1532

Answers (3)

Arount
Arount

Reputation: 10431

The good way is using subclasses, but if you can't do it, here is a way to access to self from a simple function not defined in a class:

class Bar:

    def __init__(self):
        pass

    def foo(self):
        try:
            self._foo(self)
        except AttributeError:
            raise NotImplementedError

    def set_foo(self, function):
        setattr(self, '_foo', function)

    def another_method(self):
        print "Another method from {}".format(self)


def foo(self):
    self.another_method()

bar = Bar()
bar.set_foo(foo)

bar.foo()

So, def foo(self) define a function with a single argument self, like a method. This function call a instance method another_method.

Bar.set_foo create a new attribute _foo in instance of Bar.

Finally, Bar.foo try to access to self._foo with self as argument. If _foo is do not exists, Bar.foo will raise a NotImplementedError as expected.

Like it you can access to self from foo without subclasses.

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48100

You want to create a abstract base class. For that, you need to inherit abc.ABCMeta in your base class. Then defining the method as abstract, you need to decorate it with @abstractmethod. For example:

from abc import ABCMeta, abstractmethod

class BaseClass(ABCMeta):
    @abstractmethod
    def my_method():
        pass

Then you may create the child class as:

class MyChildClass(BaseClass):
    def my_method():
        print 'my method'

Upvotes: 1

Paul H
Paul H

Reputation: 68186

You need to subclass the base class:

class myclass():
    def some_method():
        raise NotImplementedError

class my_subclass(myclass):
    def some_method():
        print("method called")

Upvotes: 1

Related Questions