在python中为静态变量分配类'staticmethods

时间:2016-10-19 08:37:47

标签: python

我有以下产生错误的类:

import sagaHelper from 'redux-saga-testing';
import { call, put } from 'redux-saga/effects';
import actions from './my-actions';
import api from './your-api';

// Your example
export function* login(action) {
    try {
        const user = yield call(api.login, action);
        return yield put(actions.loginSuccess(user));
    } catch(e) {
        yield put(actions.loginFail(e.message)); // Just changed that from "e" to "e.message"
    }
}


describe('When testing a Saga that throws an error', () => {
    const it = sagaHelper(login({ type: 'LOGIN', payload: 'Ludo'}));

    it('should have called the API first, which will throw an exception', result => {
        expect(result).toEqual(call(api, { type: 'LOGIN', payload: 'Ludo'}));
        return new Error('Something went wrong');
    });

    it('and then trigger an error action with the error message', result => {
        expect(result).toEqual(put(actions.loginFail('Something went wrong')));
    });
});

describe('When testing a Saga and it works fine', () => {
    const it = sagaHelper(login({ type: 'LOGIN', payload: 'Ludo'}));

    it('should have called the API first, which will return some data', result => {
        expect(result).toEqual(call(api, { type: 'LOGIN', payload: 'Ludo'}));
        return { username: 'Ludo', email: 'ludo@ludo.com' };
    });

    it('and then call the success action with the data returned by the API', result => {
        expect(result).toEqual(put(actions.loginSuccess({ username: 'Ludo', email: 'ludo@ludo.com' })));
    });
});

现在它无法识别MyClass。如果我删除“MyClass”python将无法识别这些功能。我知道我可以将静态方法从类外部移出作为模块函数。是否可以将它们保留在课堂中并像我一样使用它们?

1 个答案:

答案 0 :(得分:1)

更改顺序,以便在定义方法后指定字典。这样做时也不要使用MyClass

class MyClass(object):

    @staticmethod
    def _make_basic_query():
       #some code here
       pass

    @staticmethod
    def _make_query_three_aggregations():
       #some code here
       pass

    @staticmethod
    def _make_query_three_transformations(aggs):
       #some code here
       pass

    QUERIES_AGGS = {
        'query3': {
            "query": _make_basic_query,
            'aggregations': _make_query_three_aggregations,
            'aggregation_transformations': _make_query_three_transformations
        }
    }

这是有效的,因为在类声明的主体中,您可以引用方法而不需要类类型。你所引用的内容必须已经声明了。