Guest User

asyncio2

a guest
May 25th, 2020
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. try:
  2.     import os
  3.     import sys
  4.     import asyncio
  5.     print("{}".format(sys.version))
  6.     print("\n")
  7. except Exception as  e:
  8.     print("Some modules  are missing :{} ".format(e))
  9.  
  10.  
  11. class Compute(object):
  12.  
  13.     def __init__(self, num):
  14.         self.num = num
  15.  
  16.     async def square(self):
  17.         print("Computing Square : {} ".format(self.num))
  18.         await asyncio.sleep(3)
  19.         print("Square of Number is : {} ".format(self.num))
  20.         return self.num * self.num
  21.  
  22.     async def cube(self):
  23.         print("Computing cube : {} ".format(self.num))
  24.         await asyncio.sleep(3)
  25.  
  26.         # you have just defined a task
  27.         task = asyncio.create_task(coro=self.square())
  28.  
  29.         res = await task
  30.         num = res * self.num
  31.         print("Cube : {} ".format(num))
  32.         return num
  33.  
  34.  
  35. async def main():
  36.     _instance = Compute(2)
  37.  
  38.     task1 = asyncio.create_task(coro=_instance.square())
  39.     task2 = asyncio.create_task(coro=_instance.cube())
  40.  
  41.     await task1
  42.     await task2
  43.  
  44. if __name__ == "__main__":
  45.     asyncio.run(main())
  46.     # _instance =Compute(2)
  47.     # asyncio.run(_instance.cube())
Advertisement
Add Comment
Please, Sign In to add comment