如何使用另一个类中的方法结果

时间:2014-06-04 22:44:11

标签: python class

我只是在学习python中的类,我会的 想知道一个类中的方法的结果如何 用于另一个类......场景就是这样。

Class A:

    def x(self):
        #do stuff and call Class B

Class B:
    def y(self):
        #do stuff get results and pass results to Class A
        results

如何将结果传回A类? 感谢

3 个答案:

答案 0 :(得分:2)

也许你想要这个

class A:

    def x(self):
        #do stuff and call Class B
        n = 1
        n += B().y() #Instance B and call y method
        print n

class B:
    def y(self):
        #do stuff get results and pass results to Class A
        x = 10
        return x

a = A() #create a object with type A
a.x() #call x method of A class

答案 1 :(得分:1)

Class A:
    def x(self):
        #do stuff and call Class B
        my_B = B()
        theResult = my_B.y()    # you just called B's function y()

Class B:
    def y(self):
        #do stuff get results and pass results to Class A
        return results

答案 2 :(得分:0)

假设您在方法A.x中创建了B类:

Class A:

    def x(self):
        #do stuff and call Class B
        results = B().y()

Class B:
    def y(self):
        #do stuff get results and pass results to Class A
        return results

假设方法A.x获得了B类的对象:

Class A:

    def x(self, b):
        #do stuff and call Class B
        results = b.y()

Class B:
    def y(self):
        #do stuff get results and pass results to Class A
        return results