(可选)在类方法上使用装饰器 [英] Optionally use decorators on class methods

查看:81
本文介绍了(可选)在类方法上使用装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,并且为API构建了包装器。我想让用户决定他/她是否想在我从我的模块公开的方法上使用装饰器。

Im new to Python, and im building a wrapper for an api. I would want to let the user decide if he/she wants to use a decorator on methods I expose from my module.

例如:

# create a new instance
api = MyApi()

# return a simple json response with all the data related to a timetable
print api.time_table

现在用户拥有所有数据,并且可以做他/她想要的一切。例如,我想添加某种便利方法;让用户获得json的一小部分而不是整个json大响应。

Now the user has all the data, and can do whatever he/she wants. I would want to add some kind of 'convenience' methods, for example; to let the user get a small part of the json instead of the whole big json response.

我的想法是为此使用python装饰器。可选地,我的目标可能是这样的:

My idea was to use pythons decorators for this. Optionally my goal whould be something like this:

# use the method and get al the data
print api.time_table

# Optionally, get a specific part, just the shows part. (PSEUDO CODE BELOW)
@shows
print api.time_table

那不是装饰器的工作方式,但是有没有办法在现有的类方法上选择性地使用装饰器,还是装饰器总是必须包装原始方法?

Naturally, thats not how decorators work, but is there a way to optionally use a decorator on a existing class method, or does the decorator always have to be wrapping the original method?

那么,这里最Python化的方式是什么?我真的很想使用装饰器,但是如果这不是一个好主意,那就在我的 Api 类中创建更多的便捷方法就可以了。

So what is the most Pythonic way here? I really would like to use decorator, but if thats a bad idea here, im fine with just creating more 'convenience' methods inside my Api class.

推荐答案

您的选择是向您的API添加更多方法或向用户提供实用功能:

Your options are to add more methods to your API or to provide the user with utility functions instead:

from yourmodule import MyAPI

api = MyAPI

filtered_timetable = api.filter_on(something)

from yourmodule import MyAPI, filter_timetable

api = MyAPI

filtered_timetable = filter_timetable(api.time_table, something)

记住装饰器只是可调用的;语法:

Remember that decorators are just callables; the syntax:

@foo
def bar():
    pass

只是以下方面的语法糖:

is just syntactic sugar for:

def bar():
    pass
bar = foo(bar)

foo()被调用,并且返回值替换装饰的对象。通常,您将函数用作装饰器,但是没有什么说您必须仅将这些函数用作装饰器。

foo() is called, and the return value replaces the decorated object. Usually you use functions for decorators, but nothing says you have to use those functions only as decorators.

filter_timetable 可能是这样的装饰器;如果您有一个用例可同时使用。

filter_timetable could be such a decorator; if you have a usecase for using it as both.

这篇关于(可选)在类方法上使用装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆