gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:30:29 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com