【问题标题】:How to inherit derived class's subclass form base class?如何从基类继承派生类的子类?
【发布时间】:2021-08-20 05:52:35
【问题描述】:

我拥有的是这段代码

class A:
    ''' merge all services together '''
    def __init__(self):
        self.event = 'event'
    
    '''It includes all common method to all services'''
    # TODO inherit these class in others
    class B:
        def __init__(self):
            self.event = 'event'

        def get_event_type(self):
            self.event = 'event'


    class C(B):
        def __init__(self):
            self.event = 'event'
           

        class D(B):
            def __init__(self):
                self.event = 'event'
               

            def get_job_id(self):
               self.event = 'event'

这里我想用 B 继承 D 类,但是出错了

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 16, in A
File "<string>", line 21, in C
NameError: name 'B' is not defined

如果有人可以帮助我解决这个问题,为什么我会收到此错误?即使我继承了 C 类。

【问题讨论】:

  • 你想把类写成闭包还是只是缩进错误?如果不关闭,则改进结构

标签: python python-3.x class oop inheritance


【解决方案1】:

我认为这是一个缩进问题 你可以试试:

class A:
    ''' merge all services together '''
    def __init__(self):
        self.event = 'event'
    
'''It includes all common method to all services'''
# TODO inherit these class in others
class B:
    def __init__(self):
        self.event = 'event'

    def get_event_type(self):
        self.event = 'event'


class C(B):
    def __init__(self):
        self.event = 'event'


class D(B):
    def __init__(self):
        self.event = 'event'


    def get_job_id(self):
       self.event = 'event'

【讨论】:

  • 感谢您的回答,但这不是缩进错误。我想继承嵌套在类 C 和类 B 中的类 D 。并且结构应该与问题描述中提到的相同。
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2017-04-14
  • 1970-01-01
  • 2012-02-12
相关资源
最近更新 更多