繁体   English   中英

在 Python 中选择从哪个父类继承

[英]Choose which parent class inherit from in Python

我正在努力尝试在创建类时选择要继承的父类而不影响任何子类。

有一个金字塔结构的类,在顶部,我尝试选择从哪里继承: threading.Threadmultiprocessing.Process (用子类的参数指定它)。

我只在这个金字塔的第一层创建了一个返回基类的函数,代码在这里:

class ProcessClass(object):
    '''A thread with different inheritance.
    '''
    def __new__(cls, *args, **kwargs):
        thr_type = kwargs.pop("thr_type","threading")
        print("HELLO", thr_type)
        if(thr_type == "threading"):
            new_cls = threading.Thread 
        if(thr_type == "multiprocessing"):
            new_cls = multiprocessing.Process
        instance = super(ProcessClass, cls).__new__(obtain_thread_class(new_cls))
        instance.__init__(*args, **kwargs)
        return instance

def obtain_thread_class(new_cls):
    class BaseClass(new_cls):
        """Class with its methods"""
        def __init__(self, daemon=False, *args, **kwargs):
            # THREADING
            super(BaseClass, self).__init__(*args, **kwargs)
            self.daemon=daemon
        def hello(self):
            print("Hello World")
    return BaseClass

但是现在,当我尝试在子类中继承ProcessClass时,这个会丢失他的所有属性,并且无法正确传递参数(我认为这是由于__new__ )。

子示例类是:

class ExampleClass(ProcessClass):
    def __init__(self, arg1, arg2, arg3="1", *args, **kwargs):
        self.list_args = [arg1, arg2]
        print("arg3 is", arg3)
        super(ExampleClass, self)
    def hello2(self):
        print("Hello from child!")

有了这个,如果我执行:

a = ExampleClass(thr_type="threading")
print(type(a))

我获得:

HELLO threading
<class '__main__.obtain_thread_class.<locals>.BaseClass'>

但是,我只能调用hello()而不能调用hello2()

a.hello()
Hello World

a.hello2()
Traceback (most recent call last):

  File "<ipython-input-11-2505bb83de52>", line 1, in <module>
    a.hello2()

AttributeError: 'BaseClass' object has no attribute 'hello2'

我认为使用__new__是破坏儿童创作的东西。

我也尝试过使用装饰器,并看到了__metaclasses__一些东西,但在深入这些领域之前,我想知道是否有更简单的东西,因为我不是 Python 的专家。

此外,我不希望此更改影响我正在运行的任何程序(许多类都继承自ProcessClass ,但目前这只是threading.Thread )。 我试图让整个程序unnoticiable这种变化。

最后我去了作文。 没有找到如何在运行时选择继承。 但这仍然有效。

class ProcessClass(object):
    '''A thread with different inheritance.
    '''
    def __init__(self, thr_type="multiprocessing", *args, **kwargs):
        if(thr_type == "threading"):
            new_cls = threading.Thread
        if(thr_type == "multiprocessing"):
            new_cls = multiprocessing.Process
        self.thread = new_cls(*args, **kwargs)
    def start(self):
        return self.thread.start()

    def run(self):
        return self.thread.run()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM