python - 如何用Python中的新类继承来替换动态继承?

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

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

最佳答案

您可以在 Foo 之外执行 if:

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

然后继承OsSpecificClass

关于python - 如何用Python中的新类继承来替换动态继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20552859/

相关文章:

python - 如何从此网络服务下载多页数据?

python - 如何用新的绘图或绘图网格替换 matplotlib 图中以前的绘图?

java - 尝试调用方法时出错

Scala - 在包含未实现变量的 Trait 中使用字符串插值

python - 不允许迭代 tf.Tensor : AutoGraph is disabled in this function

python - NLTK Perceptron Tagger - 它识别什么是 FW(外来词)?

javascript - 如果 class true 将 url 添加到 iframe 并处理 url 列表,然后重复?

javascript - 在 JavaScript 中重用类名

c++ - 成员函数调用和C++对象模型

javascript - 为什么重置原型(prototype)不会从对象中删除属性?