【问题标题】:Python subclass not recognizing inherited parent classPython子类不识别继承的父类
【发布时间】:2014-12-02 16:37:14
【问题描述】:

我正在努力处理我的代码,特别是子类。我有一个父类,初始化时将调用其子类以用作属性,以对象列表的形式。我看过很多帖子,有人忘记打电话给父母的__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):

【问题讨论】:

  • 名称bundle 直到 类定义完成后才定义,因此subbundle 不能从它继承并且 是一个嵌套类.但是,从示例中并不清楚为什么您希望 subbundle 被继承或嵌套。
  • 你不能从“bundle”方法调用任何“subbundle”方法。这是另一种方式:“子捆绑”可以调用“捆绑”方法。子类化是为了专门化对象,而不是产生孩子
  • 因为你正在做嵌套在另一个类中的类,它不知道bundle 是什么,我认为它必须是subbundle(self)。但是您可能真正想要的是使 subbundle(bundle) 成为它自己的类,而不是嵌套的
  • 谢谢大家,我还在习惯OOP,我想封装,因为这两个东西是密切相关的

标签: python object inheritance subclass


【解决方案1】:

当我运行您的代码时,出现以下行中的错误:

class subbundle(bundle):

那是因为您试图从bundle继承您的subundle 类。我不知道这是否是你真正想要做的。让我们假设它是。

当 Python 尝试解析 .py 文件时,它会在看到 class bundle 后立即尝试找出类层次结构。当解释器到达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 的一种方法,但事实并非如此。您可能想将bundle.__init__ 中的代码更改为:

for i in range (1,self.size):
    subbundle_instance = subbundle(r, c, self.rows, self.cols)
    subchans.append(subbundle_instance)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2012-04-11
    相关资源
    最近更新 更多