PYTHON:AttributeError - 在类的成员函数中调用函数

时间:2015-08-06 19:56:29

标签: python function class

我在使用Python 2.7中的类时遇到了麻烦:

首先,我真的不知道如何正确使用__init__,所以我刚刚使用了对print的虚拟调用。我该怎么做呢?

其次,我希望成员函数readAnyFormat调用一些函数(稍后我将创建一种case语句)。我的尝试产生了AttributeError。我该如何正确地做到这一点?

我的课程如下:

class ArangeData:

        def __init__(
                    self):

            print ' '

        def readAnyFormat(
                    self,
                    config = True,
                    mypath='text.txt',
                    data_format='ASCII',
                    data_shape='shaped'):

            #Here the function should be called:'
            #NOT WORKING: 
            #AttributeError: ArangeData instance has no attribute 'readASCII'
            if data_format=='HDF5':
                readHDF5()
            elif data_format=='ASCII':
                readASCII()


            def readASCII():
                'doing stuff in here'

            def readHDF5():
                'doing other stuff in here, which is not the business of readASCII'

        def otherMemberFunction(self):
            'do not care what they are doing above!'

1 个答案:

答案 0 :(得分:2)

  • 您应该移动readASCIIreadHDF5的定义,使它们高于两个if语句。
  • 您不需要在print中使用虚拟__init__语句。如果您无需初始化,则只需使用pass,或者更好,因为@chepner发表了评论,甚至不定义__init__