2

I'm learning python and what to know what I'm doing below is correct or is there a better way to write it?

class FUNC:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def Add(self):
        x = self.a + self.b
        return x
    def Sub(self):
        y = self.a - self.b
        return y

class TASKS:
    def tsk1(self):           
        PrintObj1 = FUNC(10,20)
        print(PrintObj1.Add())
    def tsk2(self):
        PrintObj2 = FUNC(100,50)
        print(PrintObj2.Sub())

class RUNTASK:
    Obj = TASKS()
    Obj.tsk1()
    Obj.tsk2()
2
  • Looks absolutely fine, You might have been after Obj = TASKS rather than Obj = TASKS() maybe? You should not really use capitals as variables unless they are constants however. Commented Jun 25, 2018 at 22:20
  • RUNTASK looks like it should be a function, not a class. What would it mean to have a RUNTASK object? Commented Jun 25, 2018 at 22:32

2 Answers 2

1

Yes, your code looks correct, but you can also use TASKS class that contains only static methods. A static method is a method that belongs to a class rather than an instance of a class, so you don't need to create an instance of a class to invoke a static method (it's convenient in such cases):

class FUNC:

    def __init__(self,a,b):
        self.a = a
        self.b = b
    def Add(self):
        x = self.a + self.b
        return x
    def Sub(self):
        y = self.a - self.b
        return y


class TASKS:

    @staticmethod
    def tsk1():
        PrintObj1 = FUNC(10,20)
        print(PrintObj1.Add())

    @staticmethod
    def tsk2():
        PrintObj2 = FUNC(100,50)
        print(PrintObj2.Sub())

TASKS.tsk1()
TASKS.tsk2()
Sign up to request clarification or add additional context in comments.

Comments

1

What you're doing here is creating an object of another class, inside a method of a class. If you wanted to show that the FUNC class belongs completely to TASKS, you could do this:

class TASKS:
    class FUNC:
        def __init__(self,a,b):
            self.a = a
            self.b = b
        def Add(self):
            x = self.a + self.b
            return x
        def Sub(self):
            y = self.a - self.b
            return y

    @staticmethod
    def tsk1():
        PrintObj1 = TASKS.FUNC(10,20)
        print(PrintObj1.Add())

    def tsk2(self):
        PrintObj2 = self.FUNC(100,50)
        print(PrintObj2.Sub())


TASKS.tsk1()

obj = TASKS()
obj.tsk2()

This is called an inner or nested class. It's not particularly common in Python. In addition, I've shown the two ways of accessing the inner class, one using instance methods and one using static methods as suggested by @ArtsiomPraneuski (which seems more appropriate here.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.