Home > OS >  Cross Class Subclass use
Cross Class Subclass use

Time:07-17

I am experimenting with python object orientated programming. Of course I learned about inheritence and so on, but this question is very specific and I couldn't find the answer anywhere yet.

Let's say we have a class class mainClass:. In this class there is a function def func(self):. And within this function func() I want to use two custom classes. Can I and how can I use the first custom class within the second one? (Here's a example)

class custom1:
    def func1(self):
        #do something

class custom2:
    def func2(self):
        #call function func1 from class custom1 without creating another instance

class mainClass:
    def func(self):
        obj1 = custom1()
        obj2 = custom2()
        obj2.func2()

Like I said I don't want to create a second instance of custom1 within custom2. Only the one in mainClass.

Thanks for your answers :)

CodePudding user response:

what about passing it via the constructor of the first class?

class custom1:
    def func1(self):
        #do something

class custom2:
    def __init__(self, obj1):
        self._obj1 = obj1

    def func2(self):
        self._obj1.func1()


class mainClass:
    def func(self):
        obj1 = custom1()
        obj2 = custom2(obj1)
        obj2.func2()
  • Related