我正在编写一个简单的ORM,它要求我覆盖子类中的方法。根据上下文,我或者期望通过类方法或实例方法访问模型,因此我不能简单地覆盖它们。我相信这段代码很好地描述了这个问题:
import React, { Component } from 'react';
import { Route, Switch, Redirect, Link } from 'react-router-dom';
import { BrowserRouter, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from '../actions/actionCreators';
class App extends Component {
constructor() {
super();
};
render() {
return (
<div>
<a href="/"> main</a>
<a href='/info'>info</a>
<Switch>
<Route exact path="/" render={() => <h1>kawaii world</h1>} />
<Route exact path="/info" render={() => <h1>v kawaii world ;)</h1>} />
</Switch>
</div>
);
};
};
function mapStateToProps(state) {
return {
count: state.count
};
};
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
答案 0 :(得分:0)
您的B.key_fn
确实会被调用。但是你的load_all
会返回一个生成器,因为你让它yield from db_fetch_prefix
。您可以在最后运行print(B.load_all())
来检查此问题。输出将是:
python .\clsss.py
<generator object A.load_all at 0x0521A330>
使用yield from
我不知道您想要达到的目标。但是可以在子类中显示覆盖类方法的示例是:
class A:
@classmethod
def key_fn(cls, id):
raise NotImplementedError('')
@classmethod
def load_all(cls):
return cls.key_fn('foo')
class B(A):
@classmethod
def key_fn(cls, id):
return f'/keys/{id}'
print(B.load_all()) # prints "/keys/foo"
疯狂地猜测您要将key_fn
应用于您的生成器db_fetch_prefix
(下面缩写为fetch
)所产生的每个项目,下面的代码显示B.key_fn
将是也用于发电机。
def fetch(callback):
for i in range(5): # fake DB fetch
yield callback(i)
class A:
@classmethod
def key_fn(cls, id):
raise NotImplementedError('')
@classmethod
def load_all(cls):
yield from fetch(cls.key_fn)
class B(A):
@classmethod
def key_fn(cls, id):
return f'/keys/{id}'
print(list(B.load_all())) # prints ['/keys/0', '/keys/1', '/keys/2', '/keys/3', '/keys/4']