由于之前不清楚,我发布了这个场景:
class Scraper:
def __init__(self,url):
self.start_page = url
def parse_html(self):
pass
def get_all_links(self):
pass
def run(self):
#parse html, get all links, parse them and when done...
return links
现在在像 rq 这样的任务队列中
from rq import Queue
from worker import conn
q = Queue(connection=conn)
result = q.enqueue(what_function, 'http://stackoverflow.com')
我想知道这个什么函数是什么?我记得 Django 对他们的 CBV 做了类似的事情,所以我使用了这个类比,但不太清楚。
我有一个类似的类(class)
class A:
def run(self,arg):
#do something
我需要将其传递到任务队列,这样我就可以执行类似的操作
a = A()
b = a.run
# q is the queue object
q.enqueue(b,some_arg)
我想知道还有什么其他方法可以做到这一点,例如,Django 在其基于类的 View 中执行此操作,
class YourListView(ListView):
#code for your view
最终作为函数传递
your_view = YourListView.as_view()
它是如何完成的?
编辑:详细来说,django 基于类的 View 被转换为函数,因为模式函数中的参数需要一个函数。同样,您可能有一个接受以下参数的函数
task_queue(callback_function, *parameters):
#add to queue and return result when done
但是callback_function的功能可能主要在一个类中实现,该类具有一个run()方法,通过该方法运行进程。
最佳答案
我认为您正在描述一个类方法
:
class MyClass(object):
@classmethod
def as_view(cls):
'''method intended to be called on the class, not an instance'''
return cls(instantiation, args)
可以这样使用:
call_later = MyClass.as_view
后来称为:
call_later()
最常见的是,类方法用于实例化新实例,例如 dict
的 fromkeys
类方法:
dict.fromkeys(['foo', 'bar'])
返回一个新的字典实例:
{'foo': None, 'bar': None}
更新
在您的示例中,
result = q.enqueue(what_function, 'http://stackoverflow.com')
你想知道what_function
可以去那里。我在 RQ 主页上看到了一个非常相似的例子。这必须是你自己的实现。您可以使用代码调用它。它只会使用该参数调用一次,因此如果使用类,如果您想为您的 使用
替换:Scraper
,您的 __init__
应该看起来更像这样What_function
class Scraper:
def __init__(self,url):
self.start_page = url
self.run()
# etc...
如果您想使用类方法,可能如下所示:
class Scraper:
def __init__(self,url):
self.start_page = url
def parse_html(self):
pass
def get_all_links(self):
pass
@classmethod
def run(cls, url):
instance = cls(url)
#parse html, get all links, parse them and when done...
return links
然后你的 what_function
将是 Scraper.run
。
关于python - 如何将类呈现为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955919/