繁体   English   中英

Python 属性和 inheritance 错误

[英]Python error with attributes and inheritance

我在使用 Python 时遇到错误,但我不知道如何修复它。 我有一些分类,一个 class “应用程序”、“控制器”和“控制台”。 Console 继承自 Controller 和 Controller 继承自 App。

class 控制台(控制器):...

class 控制器(应用程序):...

class 应用程序():...

class Controller 有一个属性“commands”,它是一个列表。 class 控制台有一个 function “write_command”,它调用控制器的 function。

这是 class “控制台”

class Console(Controller):

def __new__(cls, *args, **kwargs):
    return super(Console, cls).__new__(cls)

def __init__(self):
    print('Init the console')

def __del__(self):
    print('Destructor console')

def write_command(self):
    command = input('Please write something: ')

    if self.exit_from_console(command):
        print('Bye')

    else:
        if self.is_valid_command(command):
            print(super().do_something(0, command))
        else:
            print('Que vergüenza, estoy algo confundido')
        self.write_command()

def is_valid_command(self, command):
    # Check if command is valid
    return super().validate_command(command)

@staticmethod
def exit_from_console(command):
    if command == 'exit':
        return True
    else:
        return False

这是控制器的 class 的代码:

class Controller(App):

def __new__(cls, *args, **kwargs):
    return super(Controller, cls).__new__(cls)

def __init__(self):

    # Temp Command list. Get it from DB
    self.commands = [('caminar', 'walk', 1),
                     ('correr', 'run', 2),
                     ('saltar', 'jump', 3),
                     ('saludar', 'hello', 4),
                     ('', '', 5),
                     ('', '', 6),
                     ('', '', 7)
                     ]

    self.users = ['0', 'System', 'Scenary']

    print('Init de controller')

def validate_command(self, command):
    # Search in local data base for command
    found = False
    the_commands = self.commands

    for i in the_commands:
        if i[0] == command.lower() or i[1] == command.lower():
            found = True
            break

    return found

def get_commands(self):
    pass

def do_something(self, user, command):
    for item in self.commands:
        if item[0] == command.lower or item[1] == command.lower:
            return super().play(user, item[2])

    return 'Nothing'

def get_commands(self):
    return self.commands

和 class 应用程序,有一个 function 播放()

错误是:

AttributeError:“控制台”object 没有属性“命令”

这是真的,但我没有使用控制台中的这个属性,而是 Controller class,它确实定义了它。

谢谢!

PD:如果这很愚蠢,我很抱歉,但我是 Python 的新手。

您没有为超级 class 调用初始化 function 您应该调用:

super(Console, self).__init__()

暂无
暂无

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

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