简体   繁体   中英

Cross Class Subclass use

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM