Stance
Stance

Reputation: 31

The correct way in python to create a class inside another class?

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()

Upvotes: 2

Views: 1327

Answers (2)

Jeff Learman
Jeff Learman

Reputation: 3277

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.)

Upvotes: 1

Artsiom Praneuski
Artsiom Praneuski

Reputation: 2319

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()

Upvotes: 1

Related Questions