Professional Python. Luke Sneeringer
Читать онлайн книгу.is happening here? The decorator creates a subclass of
Task
and returns the class. The class is callable calling a class creates an instance of that class and runs its _
init_
method
The value of doing this is that it provides a hook for lots of augmentation. The base Task
class can define much, much more than just the run
method. For example, a start
method might run the task asynchronously. The base class might also provide methods to save information about the task's status. Using a decorator that swaps out a function for a class here enables the developer to only consider the actual body of his or her task, and the decorator does the rest of the work.
You can see this in action by taking an instance of the class and running its identify
method, as shown here:
This exact approach carries with it some problems. In particular, once a task function is decorated with the @task_class
decorator, it becomes a class.
Consider the following simple task function decorated in this way:
Now, attempt to run it directly in the interpreter:
That is a bad thing. This decorator alters the function in such a way that if the developer runs it, it does not do what anyone expects. It is usually not acceptable to expect the function to be declared as foo
and then run using the convoluted foo().run()
(which is what would be necessary in this case).
Fixing this requires putting a little more thought into how both the decorator and the Task
class are constructed. Consider the following amended version:
A couple of key differences exist here. The first is the addition of the __call__
method to the base Task
class. The second difference (which complements the first) is that the @task_class
decorator now returns an instance of the TaskSubclass
, rather than the class itself.
Конец ознакомительного фрагмента.
Текст предоставлен ООО «ЛитРес».
Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.
Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.