如何在Python中将动态继承替换为要从中继承的新类



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

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

然后继承OsSpecificClass

实现这一点的一种更合适、更稳健的方法是Factory Pattern

最新更新