【发布时间】:2016-07-03 22:22:00
【问题描述】:
我收到以下错误:
Traceback (most recent call last):
File "/Users/user/repos/prodigy/Sweeper/envsweeper/lib/python2.7/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/Users/user/repos/dr/Sweeper/envsweeper/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/Users/user/repos/prodigy/Sweeper/envsweeper/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/Users/user/repos/dr/Sweeper/test.py", line 5, in <module>
from SomethingSubclass import SomethingSubclass
File "/Users/user/repos/dr/Something/SomethingSubclass.py", line 18, in <module>
class SomethingSubclass(SomethingBaseclass):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
这是Base类中的代码:
import os
import sys
import inspect
from settings import picklePass, masterMap
from decimal import Decimal
CURRENTDIR = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(CURRENTDIR)
sys.path.insert(0, parentdir)
from libs.pickler.pickler import Pickler
import logging
class BaseClass(object):
def __init__(self, address, fee, msg_body):
self.address = address
self.fee = (fee)
self.msg_body = msg_body
这将是SubClass 中引发错误的代码,文件名:SubClass.py:
import os
import sys
import inspect
import Sweeper
CURRENTDIR = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(CURRENTDIR)
sys.path.insert(0, parentdir)
from libs.deterministic import electrum_privkey
from libs.transaction import sign, mksend
import logging
sys.path.insert(0, CURRENTDIR)
class SubClass(BaseClass):
def __init__(self, address, fee, msg_body):
BaseClass.__init__(self, address, fee, msg_body)
这就是子类的实例化方式:
....
module = __import__('SubClass')
class_ = getattr(module, 'SubClass')
有什么线索可能是错的吗?
【问题讨论】:
-
SomethingSubClass.py文件在您的回溯中来自哪里?为什么要使用class SomethingSubclass.py(...),那不是有效的 Python 代码。我也没有在您发布的代码中看到任何元类。错误的完整回溯是什么? -
关于发布的代码还有很多其他问题。为什么要和
sys.path搞混?为什么要使用与类名匹配的模块名,Python不是java,模块不必使用与包含在其中的类相同的名称;约定是使用 lower_case_with_underscores 作为模块名称(这里可以尽量减少下划线)。 -
那么就是使用
__import__而不是直接导入;您可能对此有一个用例,但它肯定与手头的问题无关;你能在没有所有额外内容的情况下生成minimal reproducible example 吗? -
好的,公平的问题。我将尝试以相同的顺序回答它们:1)我没有使用类 SomethingSubclass.py(...),我不确定你从哪里得到这个。 2)我需要更改sys路径以访问其他目录中的库并导入它们:3)您对模块名称绝对正确,我将更改此,谢谢:)。 4)我使用 import 正是因为你提到的那个用例,我需要根据参数导入不同的子类。我特别为这个例子硬编码了这个。
-
对于#1,仔细查看您发布的回溯。
标签: python inheritance import module