Python Forum
Trying to access next element using Generator(yield) in a Class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to access next element using Generator(yield) in a Class
#1
I have created a Class and used generator in a method which is supposed to yield even numbers between start and stop range. When trying to use next() of yield from the Class Obj, it is printing the same number. Is this not the right way to access?

# Creating Class Evem
class Even:
    # Constructor
    def __init__(self, start, stop, reverse=False):
        self.start = start
        self.stop = stop
        self.reverse = reverse
        # self.nums = []

    # Creating filter method using yeild/Generator
    def filter_even(self):
        for i in range(self.start, self.stop + 1):
            if i % 2 == 0:
                yield i


# Creating an Obj of class Even
even_nums = Even(10, 50, False)

# Making sure what's in the obj I have created
print(even_nums.__dict__)
# {'start': 10, 'stop': 50, 'reverse': False}


# Trying to print the yield result one by one
print(even_nums.filter_even().__next__())
print(even_nums.filter_even().__next__())
print(even_nums.filter_even().__next__())
print(even_nums.filter_even().__next__())

# Q: Why is printing the same element??
# 10
# 10
# 10
# 10
Am I not calling it the right way?
print(even_nums.filter_even().__next__())
Reply


Messages In This Thread
Trying to access next element using Generator(yield) in a Class - by omm - Oct-19-2020, 01:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  yield from akbarza 4 311 Apr-19-2024, 07:58 PM
Last Post: DeaD_EyE
  yield usage as statement or expression akbarza 5 819 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  How can I access objects or widgets from one class in another class? Konstantin23 3 1,023 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Using list comprehension with 'yield' in function tester_V 5 1,268 Apr-02-2023, 06:31 PM
Last Post: tester_V
  [Solved] Novice question to OOP: can a method of class A access attributes of class B BigMan 1 1,325 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  dict class override: how access parent values? Andrey 1 1,648 Mar-06-2022, 10:49 PM
Last Post: deanhystad
  Access instance of a class Pavel_47 5 2,101 Nov-19-2021, 10:05 AM
Last Post: Gribouillis
  access share attributed among several class methods drSlump 0 1,072 Nov-18-2021, 03:02 PM
Last Post: drSlump
  Tuple generator, and function/class syntax quazirfan 3 3,907 Aug-10-2021, 09:32 AM
Last Post: buran
  Create Generator in the Class quest 1 2,140 Apr-15-2021, 03:30 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020