1

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

2 Answers 2

3

You can do the if outside of Foo:

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

And then inherit from OsSpecificClass.

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

1 Comment

Sometimes thinking too much at complex implementations keeps you from seeing the obvious and most efficient solution. Thank you sir. Walking away in shame...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.