skamsie
skamsie

Reputation: 2726

How to replace dynamic inheritance with a new class to inherit from in Python?

So I have these OS specific classes and some other class that inherits from one of them depending on the OS where we execute. The problem is, I really don't like the dynamic way I am using to check the condition (only way I came up with) so I would like to create a new class that would just check the condition and then return the appropriate class that I can use to inherit from. So here is what I have:

import os

class NewClass(object):
  def __init__(self, name):
    self.name = name

  def AnotherMethod(self):
    print 'this is another method for the base class ' + self.name

  def SomeMethod(self):
    raise NotImplementedError('this should be overridden')

class MacClass(NewClass):
  def __init__(self, name):
    super(MacClass, self).__init__(name)

  def SomeMethod(self):
    print 'this is some method for Mac ' + self.name

class WinClass(NewClass):
  def __init__(self, name):
    super(WinClass, self).__init__(name)

  def SomeMethod(self):
    print 'this is some method for Windows ' + self.name


class Foo(MacClass if os.name == 'posix' else WinClass):
  def __init__(self):
    super(Foo, self).__init__('foo')

my_obj = Foo()

#On Mac:  
my_obj.SomeMethod() #this is some method for Mac foo
my_obj.AnotherMethod() #this is some method for Mac foo

#On Win:
my_obj.SomeMethod() #this is some method for Win foo
my_obj.AnotherMethod() #this is some method for Win foo

What I would like to do:

class Class(NewClass):
  - some way to automagically return MacClass or WinClass depending on the OS

class Foo(Class):
  def __init__(self):
    super(Foo, self).__init__('foo')

my_obj = Foo()

This way would be also nicer if I wanted to have other classes that want to inherit from this one, so I don't do the check every time

Upvotes: 1

Views: 95

Answers (2)

aruisdante
aruisdante

Reputation: 9075

A more proper and robust way to do this would be the Factory Pattern

Upvotes: 0

Amir Rachum
Amir Rachum

Reputation: 79625

You can do the if outside of Foo:

OsSpecificClass = MacClass if os.name == 'posix' else WinClass

And then inherit from OsSpecificClass.

Upvotes: 3

Related Questions