0

I've attempted to create a Python interface class hierachy that looks something like:

class Axis(object, metaclass=ABCMeta): def __init__(self): # Do stuff... class LinearAxis(Axis, metaclass=ABCMeta): @abstractmethod def move_linear(self, move_um): pass def __init__(self): # Do stuff... Axis.__init__(self) class RotationalAxis(Axis, metaclass=ABCMeta): @abstractmethod def move_rotate(self, move_degree): pass def __init__(self): # Do stuff... Axis.__init__(self) class XAxis(LinearAxis, metaclass=ABCMeta): def __init__(self): # Do stuff... LinearAxis.__init__(self) 

So basically an interface sort of like that with a bunch more functions everywhere and stuff in the constructors etc...

Then I go to derive off my interface:

class AnAxis(Axis): def __init__(self): # Do stuff... Axis.__init__(self) class AnLinearAxis(AnAxis, LinearAxis): def move_linear(self, move_um): pass def __init__(self): # Do stuff... AnAxis.__init__(self) LinearAxis.__init__(self) class AnRotationalAxis(AnAxis, RotationalAxis): def move_rotate(self, move_degree): pass def __init__(self): # Do stuff... AnAxis.__init__(self) RotationalAxis.__init__(self) class AnXAxis(AnLinearAxis, XAxis): def __init__(self): # Do stuff... AnLinearAxis.__init__(self) XAxis.__init__(self) 

I'm trying to work out how to call the constructors properly. The way I have it, I'm pretty sure I call the interface constructors many times... So it's wrong... Is there a preferred way to do it? (Perhaps I don't call constructors in the interface classes, or I only call the interface constructor at the end up my implementation class.)

Also, I've never coded in this style and am open to better ways to code this.

2
  • 1
    Why are you passing metaclass=ABCMeta to your __init__ method? Also you should consider using super Commented Mar 12, 2016 at 13:18
  • That was a typo! Fixed, thanks. Commented Mar 12, 2016 at 13:25

1 Answer 1

2

You're probably looking for the super() function. Calling super().something() calls the method something() of the parent class. It makes sure (using __mro__) to call the parent classes' method only once.

i.e. your code will look like this:

class AnLinearAxis(AnAxis, LinearAxis): def move_linear(self, move_um): pass def __init__(self): # Do stuff... super().__init__() 

Keep in mind you do not need to pass self or the metaclass. The metaclass passes by the inheritance. Also, you do not need to call super more than once. Super will call all of the parent classes' methods automatically.

Regarding the interface, it looks good but there's no need to pass metaclass=ABCMeta if the class you're inheriting from already has it. The metaclass is passed on by inheritance.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.