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

时间:2013-12-12 19:49:45

标签: python class inheritance

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

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

如果我想让其他类继续从这个类继承,这种方式也会更好,所以我不会每次都进行检查

2 个答案:

答案 0 :(得分:3)

您可以在if之外执行Foo

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

然后继承自OsSpecificClass

答案 1 :(得分:0)

更合适,更健壮的方法是Factory Pattern