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

您好,我刚刚开始使用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)

您在代码中的做法是从模块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'
链接地址: http://www.djcxy.com/p/40929.html

上一篇: Simple Inherit from class in Python throws error

下一篇: python: write input to file and save it