如何将课程作为一种功能?

时间:2014-09-21 04:49:10

标签: python django function oop python-rq

由于之前不清楚我发布了这种情况:

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')

我想知道这个what_function会是什么?我记得Django和他们的CBV做了类似的事情,所以我使用了这个类比,但它并不是那么清楚。


我有一个像

这样的课程
class A:
    def run(self,arg):
        #do something

我需要将其传递给任务队列,因此我可以执行类似

的操作
a = A()
b = a.run
# q is the queue object
q.enqueue(b,some_arg)

我想知道有什么其他方法可以做到这一点,例如,Django在基于类的视图中做到了,

class YourListView(ListView):
    #code for your view

最终作为函数传递

your_view = YourListView.as_view()

怎么做?

编辑:详细说明,django基于类的视图转换为函数,因为模式函数中的参数需要一个函数。同样,您可能有一个接受以下参数的函数

task_queue(callback_function, *parameters):
    #add to queue and return result when done

但是callback_function的功能可能主要在一个类中实现,该类有一个run()方法,通过该方法运行该进程。

1 个答案:

答案 0 :(得分:3)

我认为您正在描述classmethod

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' s fromkeys classmethod:

dict.fromkeys(['foo', 'bar'])

返回一个新的dict实例:

{'foo': None, 'bar': None}

更新

在您的示例中,

result = q.enqueue(what_function, 'http://stackoverflow.com')

你想知道what_function可以去那里。我在RQ主页上看到了一个非常相似的例子。这必须是你自己的实现。它将成为您可以使用代码调用的东西。只使用该参数调用一次,因此如果您使用某个类,则__init__看起来应该更像这样,如果您想使用Scraper作为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