这是我的课程文件(称为myclasses.py):

class wave:
    def __init__(self, name = "", xdelta = 1)
        self.name = name
        self.xdelta = xdelta

    def loadbinary(bpath):
        print(bpath)


到目前为止,我已经去除了其他细节(加载二进制文件代码等),而当我运行以下命令时,我得到了一个错误输出:

import myclasses
a = myclasses.wave
a.loadbinary('TEST')


错误:

TypeError: loadbinary() missing 1 required positional argument: 'bpath'


我尝试将loadbinary定义更改为“ loadbinary(self,bpath)”,但随后给出了相同的错误。我也尝试过用“ pass”替换“ print”代码,使其不执行任何操作,但这仍然给我错误。我也尝试运行以下命令:

a.loadbinary(bpath='TEST')


...但是这将错误更改为:loadbinary()缺少1个必需的位置参数:'self'

在这一点上,我不确定发生了什么。该类的定义是基本的,并且不会继承其他类,并且据我所知,我遵循的是python文档中针对此处显示的类的代码:https://docs.python.org/2/tutorial/classes.html

我使用的是Python 3.4.3,这发生在运行于PyCharm 4.5.1的iPython 3.1.0中。如果直接在命令提示符下(OS X终端)在iPython 3.1.0中运行它,则会得到以下错误输出:

unbound method loadbinary() must be called with wave instance as first argument (got str instance instead)

最佳答案

您从未实例化该类。改为这样做:

class wave:
    def __init__(self, name = "", xdelta = 1)
        self.name = name
        self.xdelta = delta

    def loadbinary(self, bpath):
        print(bpath)


要么...

class wave:
    def __init__(self, name = "", xdelta = 1)
        self.name = name
        self.xdelta = delta

    @staticmethod
    def loadbinary(bpath):
        print(bpath)


然后...

import myclasses
a = myclasses.wave() # the brackets instantiate the class
a.loadbinary('TEST')

10-06 07:49