Skip to main content
 首页 » 编程设计

python之"AttributeError: ' 模块 ' object has no attribute"数组

2024年10月25日9dflying

这应该是一道垒球题。

我有一个名为 Table 的自定义类,其方法包括 getTableName

class table(object): 
    def __init__(self, tableName, aliasName = 'none'): 
        """Create assign a name""" 
        self.tableName = tableName 
        if aliasName == 'none': 
            self.aliasName = tableName 
        else: 
            self.aliasName = aliasName 
        self.columns = [] 
        self.relatedTables = [] 
    def getTableName (self): 
        return self.tableName 

在一个单独的脚本中我创建了一个表数组

import table 
tables = [] 

然后我追加表格数组。

def appendTables(newTable): 
    #check list of tables for match 
 
    #if first batch of tables just append to tables 
    if len(tables) == 0: 
        tables.append(newTable) 
        return 
    found = False 
    for oTable in tables: 
        print "type newTable"  #type newTable 
        print type(newTable)   #<class 'table.table'> 
        print "type oTable"    #type oTable 
        print type (oTable)    #<type 'module'> 
        a = newTable.getTableName()  #OK 
        b = oTable.getTableName()   #CRASH "AttributeError: 'module' object has no attribute 'getTableName'" 

为什么Python不识别这个类?

请您参考如下方法:

如果类 table 定义在文件 table.py 中,则您需要其中之一

from table import table 

或使用table.table 作为类名。此外,按照惯例,用户定义的类名应该以大写字母开头,这样您的代码看起来像

class Table(object): 

和

from table import Table 

和

table.Table