python 类初始化参数校验_Python:当超类接受不同的参数时进行初始化的正确方法?...

If I've got three classes like this:

class BaseClass(object):

def __init__(self, base_arg, base_arg2=None):

...

class MixinClass(object):

def __init__(self, mixin_arg):

...

class ChildClass(BaseClass, MixinClass):

def __init__(self, base_arg, mixin_arg, base_arg2=None):

???

What is the correct way to initialize MixinClass and BaseClass?

It doesn't look like I can use super because the MixinClass and the BaseClass both accept different arguments… And two calls, MixinClass.__init__(...) and BaseClass.__init__(...), will could cause the diamond inheritence problem super is designed to prevent.

解决方案

Basically, in Python, you can't support this type of inheritance safely. Luckily you almost never need to, since most methods don't care what something is, only that it supports a particular interface. Your best bet is to use composition or aggregation: have your class inherit from one of the parent classes, and contain a reference to an instance of the second class. As long as your class supports the interface of the second class (and forwards messages to the contained instance) this will probably work out fine.

In the above example (where both classes inherit from object) you can (probably) safely just inherit from both classes and call both constructors using MixinClass.__init__ and BaseClass.__init__. But note that's not safe to do if the parent classes call super in their constructors. A good rule of thumb is to use super if the parent classes use super, and __init__ if the parent classes use __init__, and hope you're never trapped having to inherit from two classes which chose different methods for initialization.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Flask 中,可以使用 Flask-RESTful 或 Flask-Inputs 等第三方库来实现接口参数校验。 Flask-RESTful: Flask-RESTful 提供了 RequestParser 类来进行参数解析和校验,示例代码如下: ```python from flask_restful import reqparse, abort, Api, Resource # 初始化 RequestParser 对象 parser = reqparse.RequestParser() # 添加参数校验规则 parser.add_argument('name', type=str, required=True, help='Name cannot be blank') parser.add_argument('age', type=int, required=True, help='Age cannot be blank') class User(Resource): def post(self): # 解析参数 args = parser.parse_args() # 校验参数 if args['name'] == 'Tom': abort(400, message='Name already exists') # 处理业务逻辑 user = {'name': args['name'], 'age': args['age']} return user, 201 # 注册路由 api = Api(app) api.add_resource(User, '/user') ``` 上述代码中,我们创建了一个名为 User 的资源类,其中 post 方法用于处理 POST 请求。在 post 方法中,我们首先使用 RequestParser 对象解析参数,然后校验参数是否符合要求,最后处理业务逻辑并返回结果。 Flask-Inputs: Flask-Inputs 提供了多种参数校验器,包括字符串长度、数字范围、正则表达式等,示例代码如下: ```python from flask import Flask, jsonify from flask_inputs import Inputs from flask_inputs.validators import JsonSchema # 初始化 Inputs 对象 inputs = Inputs() # 添加参数校验规则 schema = { 'type': 'object', 'properties': { 'name': {'type': 'string', 'minLength': 1}, 'age': {'type': 'integer', 'minimum': 0, 'maximum': 200} }, 'required': ['name', 'age'] } inputs.add('json', JsonSchema(schema=schema)) @app.route('/user', methods=['POST']) def create_user(): # 校验参数 if inputs.validate(): # 处理业务逻辑 user = {'name': inputs.json['name'], 'age': inputs.json['age']} return jsonify(user), 201 else: return jsonify(errors=inputs.errors), 400 ``` 上述代码中,我们创建了一个名为 create_user 的路由,其中使用 Inputs 对象添加了参数校验规则,然后在路由处理函数中校验参数并处理业务逻辑。如果参数校验失败,我们将返回 400 错误和错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值