简体   繁体   English

跨类子类使用

[英]Cross Class Subclass use

I am experimenting with python object orientated programming.我正在尝试使用 python 面向对象编程。 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: .假设我们有一个class mainClass: In this class there is a function def func(self): .在这个类中有一个函数def func(self): And within this function func() I want to use two custom classes.在这个函数func()中,我想使用两个自定义类。 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 .就像我说的,我不想在custom2中创建custom1的第二个实例。 Only the one in mainClass .只有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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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