为什么这个函数应该是静态的?

时间:2015-10-24 08:23:57

标签: python oop python-3.x pycharm

我从OOP开始。我有一个使用@staticmethod的课程。这会调用其他类的方法。

我的代码:

@staticmethod
def import_plane(self, matriculation):

    try:
        plane_file = '{}{}{}'.format(
            paths.planes, matriculation.upper(),
            project.aircraft_ext)

        with open(plane_file, 'r') as plane_file:
            reader = json.load(plane_file)

            plane = Plane.Plane(
                reader['Matriculation'],
                reader['Type'],
                reader['OACI'],
                reader['Colors'],
                self._get_speeds(reader),
                self._get_fuel(reader),
                self._get_runway(reader),
                reader['RDBA'],
                reader['Transponder'],
                reader['Turbulance'],
                reader['Certification'],
                self._get_equipments(reader),)

    except Exception as exception:
        return str(exception)

    else:
        return plane


def _get_speeds(self, reader):
    return {
        'crusing':    reader['Speeds']['Crusing'],
        'climb':      reader['Speeds']['Climb'],
        'vz_climb':   reader['Speeds']['VzClimb'],
        'descent':    reader['Speeds']['Descent'],
        'vz_descent': reader['Speeds']['VzDescent'],
        'vso':        reader['Speeds']['VSO'],
        'vfe':        reader['Speeds']['VFE'],
        'vno':        reader['Speeds']['VNO'],
        'vne':        reader['Speeds']['VNE'],
        'vx':         reader['Speeds']['Vx'],
        'vy':         reader['Speeds']['Vy']
    }

错误: 方法_get_speeds()应该是静态的

我正在使用PyCharm IDE

1 个答案:

答案 0 :(得分:3)

_get_speeds方法在其范围内的任何位置都没有使用self变量(类的实例) - 这就是为什么它的&#c} &&&&&&& #34;静态&#34 ;.您可以轻松地调用此方法,而无需实例化类:

MyClass._get_speeds(reader)

普通实例方法只能在类实例上工作 - 事实上,您的import_plane方法使用self,而应该是staticmethod

questiontop answer非常值得一读。