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

2024-09-30 10:38:40 发布

您现在位置: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__是破坏儿童创造的东西。你知道吗

我也尝试过使用decorator,也看到了__metaclasses__的一些东西,但是在深入研究这些领域之前,我想知道是否有更简单的方法,因为我不是python方面的专家。你知道吗

另外,我不希望这个更改影响我正在运行的任何程序(许多类是从ProcessClass继承的,但目前这只是threading.Thread)。我试着为整个程序保留这个更改。你知道吗


Tags: selfnewdeftypeargsthreadkwargsclass
1条回答
网友
1楼 · 发布于 2024-09-30 10:38:40

最后我选择了作文。找不到如何在运行时选择继承。但这仍然有效。你知道吗

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

相关问题 更多 >

    热门问题