1

I was kinda playing around with Object Oriented Programming in python and ran into an error i havent encountered before..:

class Main:
    def __init__(self, a , b):
        self.a = a
        self.b = b

    def even(self):
        start = self.a
        slut = self.b
        while start <= slut:
            if start % 2 == 0:
                yield start
            start += 1

    def odd(self):
        start = self.a
        slut = self.b
        while start <= slut:
            if start % 2 != 0:
                yield start
            start += 1

    def display():
        evens = list(num.even())
        odds = list(num.odd())
        print(f"{evens}'\n'{odds}")

num = Main(20, 50)

Main.display()

Take a look at the last class method, where there shouldent be a 'self' as a parameter for the program to Work..Why is that? I thought every class method should include a 'self' as a parameter? The program wont work with it

1 Answer 1

1

There should be a self parameter, if it's intended to be an instance method, and you would get an error if you tried to use it as so, i.e., num.display().

However, you are calling it via the class, and Main.display simply returns the function itself, not an instance of method, so it works as-is.

Given that you use a specific instance of Main (namely, num) in the body, you should replace that with self:

def display(self):
    evens = list(self.even())
    odds = list(self.odd())
    print(f"{evens}'\n'{odds}")

and invoke it with

num.display()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.