Calling variables from Class to another

时间:2018-03-25 19:56:45

标签: python

I find myself in this situation:

class C2(x2, f2):
    def __init__(self):
        super(x2, self).__init__()
        self.setupUi(self)

And:

class C1(x1, f1):
    def __init__(self):
        super(x1, self).__init__()
        self.setupUi(self)
        text = self.FMB.text()

And I would like to be able to pass the text variable to class C2. I have tried to use the following method:

class C2(x2, f2):
    def __init__(self):
        super(x2, self).__init__()
        self.setupUi(self)
        def f3(t):
            var = t
            self.v2.setText(t)

# Here the variable 'text' from C1 is assigned to a lineedit in C2

class C1(x1, f1):
    def __init__(self):
        super(x1, self).__init__()
        self.setupUi(self)
        text = self.FMB.text()
        C2.f3(text)

But it is not possible to carry out the commented assignment. How can I do it?

2 个答案:

答案 0 :(得分:1)

As @cricket_007 mentioned in the comments, you can't call C2.f3() since f3 is not a class function, but it is a method of C2 which is different.

So what you can do.

1) Call f3 as a method:

class C2:
    def f3(self, t):
        ...

And then use it like:

C2().f3(text)

Or

2) Make f3 a class function and use it as it is in your code:

class C2:
    @classmethod
    def f3(cls, t):
        ....

答案 1 :(得分:0)

Your terminology is a little confusing. Do you want to pass the text to the class C2 (meaning every instance of C2 will have identical text), or to an instance of C2 (meaning each instance can have its own text value)?

Assuming you meant the latter, you'll have to change f3() to add a self parameter. You'll also need to pass an instance of C2 into C1.__init__()