简体   繁体   中英

python - getting specific generator data from the generator

let's start with the code

class MyClass:
   def __init__(self):
      self.elemplusone = None
      self.elemplustwo = None
      self.data = self.generate_data()
      
   def generate_data(self):
      for elem in range(10):
         yield elem+1, elem+2

I need to get the first and the second element of generator. Right now, I'm calling it outside the class after creating an object:

a_generator = MyClass()
c = next(a_generator.data)
elemplusone = c[0]
elemplustwo = c[1]

but I need them to be specified (as separate generators) in the class and I can't create two generator methods.

Thanks

I also don't quite understand what you mean exactly. But does this help you?

class MyClass:
   def __init__(self):
      self.data = self.generate_data()
      self.update_elements()

   def update_elements(self):
      self.elemplusone, self.elemplustwo = [x for x in next(self.data)]

   def generate_data(self):
      for elem in range(10):
          print("Yielded")
          yield elem + 1, elem + 2

a_generator = MyClass()

a_generator.elemplusone is 1 and a_generator.elemplustwo is 2.

Now you could call a_generator.update_elements() to yield your elements again and continue in your generator. Please let me know if this helps you. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM