我有以下问题:
我想在另一个类中调用一个蜘蛛,比如Ruby on Rails中的Jobs。例如:
class Foo:
MySpider()
然后,调用Foo()来执行我的蜘蛛。我不知道我的观点是否足够明确,但我会感激任何帮助:)
答案 0 :(得分:0)
您可以通过多种方式完成此操作(即使使用函数式编程),但我只想向您展示一些:
<强> 1。构造强>
你可以在MySpider
的构造函数中实例化(我认为你的意思是“call”)Foo
:
class MySpider(object):
def __init__(self):
super().__init__()
print('In MySpider __init__.')
class Foo(object):
def __init__(self):
super().__init__()
print('In Foo __init__.')
MySpider()
Foo()
'''
prints:
In Foo __init__.
In MySpider __init__.
'''
但请注意,需要创建Foo
的新实例才能实例化并保留对MySpider
的引用。如果您需要保留引用,只需将self.my_spider = MySpider()
放入__init__
。
<强> 2。添加__call __
除__init__
方法外,您还可以添加__call__
方法。这基本上做的是允许直接调用实例化对象。如果您拥有return self
,则允许调用链发生:
class Foo(object):
def __call__(self, *args, **kwargs):
print('In Foo __call__.')
MySpider()
return self
Foo()()()
'''
prints:
In Foo __init__.
In MySpider __init__.
In Foo __call__.
In MySpider __init__.
'''