首页 文章

从Python中的类继承简单会引发错误

提问于
浏览
-1

嗨,我刚开始使用Python,我目前正在为移动设备开发UI测试应用程序,我必须处理自定义渲染的软键盘 .

Button.py

class Button():
    def __init__(self, name, x, y, x2=None, y2=None):
        self.name = name
        self.x = x
        self.y = y
        self.x2 = x2
        self.y2 = y2

KeyboardKey.py

import Button
class KeyboardKey(Button):
    def __init__(self, name, x, y):
        super(self.__class__, self).__init__(name, x, y)

那是我的错误:

Traceback (most recent call last):
  File "/home/thomas/.../KeyboardKey.py", line 2, in 
    class KeyboardKey(Button):
TypeError: Error when calling the metaclass bases
    module.__init__() takes at most 2 arguments (3 given)

1 回答

  • 4

    你在代码中的方式,你继承自模块 Button ,而不是类 . 你应该继承类 Button.Button .

    为了避免将来出现这种情况,我强烈建议使用小写和大写类来命名模块 . 所以,更好的命名将是:

    import button
    class KeyboardKey(button.Button):
        def __init__(self, name, x, y):
            super(self.__class__, self).__init__(name, x, y)
    

    python中的模块是普通对象(类型为types.ModuleType),可以继承,并且具有 __init__ 方法:

    >>> import base64
    >>> base64.__init__
    <method-wrapper '__init__' of module object at 0x00AB5630>
    

    见用法:

    >>> base64.__init__('modname', 'docs here')
    >>> base64.__doc__
    'docs here'
    >>> base64.__name__
    'modname'
    

相关问题