Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explain how to make a class behave like a range #541

Open
roiser opened this issue Jan 15, 2025 · 1 comment
Open

Explain how to make a class behave like a range #541

roiser opened this issue Jan 15, 2025 · 1 comment
Labels
Advanced Content for the "advanced" course

Comments

@roiser
Copy link
Member

roiser commented Jan 15, 2025

No description provided.

@roiser roiser added the Advanced Content for the "advanced" course label Jan 15, 2025
@Ncrharsh
Copy link

If you want a class to behave like Python's range, it needs to do two main things:

Remember the range details: You need to keep track of where the range starts, where it should end, and how it steps (e.g., count by 1, 2, -1, etc.).

Know how to give the next number: When someone uses the class in a loop (like for x in MyRange), it needs to know what number to give next and when to stop.

Here’s how you’d do it step by step:

First, you make a init function. This is the setup where you save start, stop, and step.
Then, define iter. This makes the class an "iterable," meaning Python knows you can loop over it.
Finally, write next, where you calculate the next number to give out. If you're done (like the range is over), you tell Python to stop.

i hope this will help i can give example by code too if u want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Advanced Content for the "advanced" course
Projects
None yet
Development

No branches or pull requests

2 participants