在Python中,如何用一个要继承的新类替换动态继承?

在Python中,如何用一个要继承的新类替换动态继承?,python,class,inheritance,Python,Class,Inheritance,因此,我有这些特定于操作系统的类和一些其他类,它们根据我们执行的操作系统从其中一个继承而来。问题是,我真的不喜欢我用来检查条件的动态方式(我唯一想到的方式),所以我想创建一个新类,它只检查条件,然后返回我可以用来继承的适当类。这就是我所拥有的: import os class NewClass(object): def __init__(self, name): self.name = name def AnotherMethod(self): print 'this

因此,我有这些特定于操作系统的类和一些其他类,它们根据我们执行的操作系统从其中一个继承而来。问题是,我真的不喜欢我用来检查条件的动态方式(我唯一想到的方式),所以我想创建一个新类,它只检查条件,然后返回我可以用来继承的适当类。这就是我所拥有的:

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
我想做的是:

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()

如果我想从这个类继承其他类,这种方法也会更好,所以我不会每次都进行检查,你可以在
Foo
之外执行
if

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

然后继承自
ossspecificclass

一种更合适、更健壮的方法是

有时在复杂的实现中考虑太多会让您看不到明显且最有效的解决方案。谢谢你,先生。羞愧地走开。。。