Python子类不识别继承的父类

时间:2014-12-02 16:37:14

标签: python object inheritance subclass

我正在努力处理我的代码,特别是子类。我有一个父类,初始化时会以对象列表的形式将其子类称为属性。我看过很多帖子,其中一个人忘记拨打父母的__init__()。我的问题不同,因为父母正在调用子类,我不想调用它。

我收到以下错误:

NameError: name 'bundle' is not defined

我很困惑因为它被明确定义为父类。有什么想法吗?

class bundle(object):
"""Main object to hold graphical information"""
    def __init__(self, size,nzone):
        self.size = size
        self.rows = math.sqrt(size)
        self.cols = math.sqrt(size)
        subchans = []
        r = 1
        c = 1 
        for i in range (1,self.size):
            subchans.append(bundle.subbundle(r,c,self.rows,self.cols))
            r += 1            
            if r > self.rows :
                r = 1
                c += 1
    class subbundle(bundle):
        """ Defines geometry to represent subbundle"""
        def  __init__(self, row, col, rows,cols):

1 个答案:

答案 0 :(得分:1)

当我运行您的代码时,我收到了以下行中的错误:

class subbundle(bundle):

那是因为您正试图从<{1}} 继承您的subundle班级。我不知道那是不是你真正想做的事情。让我们假设它是。

当Python尝试解析bundle文件时,它会在看到.py后立即尝试找出类层次结构。当口译员到达class bundle时,它还不知道({1}}是什么。将其移至与class subbundle(bundle)

相同的级别
bundle

您将不再看到当前的错误,并会开始看到一个新错误:class bundle这是因为它试图将class bundle(object): def __init__(self, size,nzone): self.size = size [ . . .] class subbundle(bundle): """ Defines geometry to represent subbundle""" def __init__(self, row, col, rows,cols): [ . . . ] 视为一种方法type object 'bundle' has no attribute 'subbundle',但不是。您可能希望将bundle.subbundle中的代码更改为:

class bundle

PS :通常使用大写字母(又名 CamelCase )命名您的课程是一种很好的做法。请参阅https://www.python.org/dev/peps/pep-0008#class-names

相关问题