Python:在类和实例和方法之间传递值

时间:2016-04-16 23:04:07

标签: python python-2.7 class python-3.x

几天前,我问过在这些类的实例之间传递值是我的帖子here 这个问题很容易解决,尤其是运动。 但现在我无法在方法之间传递对象。

示例代码:

class MyClassA(object):
    def function1(self):
        entry = input("Insert a value ::: ")
        b = MyClassB(entry) #To pass the variable entry to class MyClassB
        d = MyClassB()
        d.function2()
        c = MyClassC(b.k) #Initializied MyClassC to be ready for receive the value p
        self.x = d.f #To get back the value k from MyClassB function2()
        print(self.x)
        self.x1 = c.p #To get back the value k from MyClassC
        print(self.x1)

class MyClassB(object):
    def __init__(self,M):
        self.f = M
        self.k = 0
    def function2(self):
        self.k = self.f * 10 # k will contain (the value entry from MyClassA *10)
        c = MyClassC(self.k) #To pass variable k to class MyClassC

class MyClassC(object):
    def __init__(self,passedVar):
        self.p = passedVar + 0.1 # p will contain (the value entry from MyClassB + 0.1)

h = MyClassA()
h.function1()

否则,每当我尝试使用instanace时,它都会正常工作,但在方法之间并不是那么固定。 上次我的代码应该给出这种结果:

Insert a value ::: 9 (assume the user typed 9 here)

所以输出应该是:

90
90.1

这里我的代码编译说

d = MyClassB()
TypeError: __init__() takes exactly 2 arguments (1 given)

我可以修改我的代码>它不需要仅适用于实例;我需要一些类

中的一些功能

2 个答案:

答案 0 :(得分:1)

您需要将某些内容传递给MyClassb()的构造函数...

答案 1 :(得分:0)

好的我的问题是

d = MyClassB() d.function2()

Statu现在已经修好了,我顺便说一句! 正确的代码是这样的:

class MyClassA(object):
    def function1(self):
        entry = input("Insert a value ::: ")
        b = MyClassB(entry) #To pass the variable entry to class MyClassB
        b.function2()
        c = MyClassC(b.k) #Initializied MyClassC to be ready for receive the value p
        self.x = b.f #To get back the value k from MyClassB function2()
        print(self.x)
        self.x1 = c.p #To get back the value k from MyClassC
        print(self.x1)

class MyClassB(object):
    def __init__(self,M):
        self.f = M
    def function2(self):
        self.k = self.f * 10 # k will contain (the value entry from MyClassA *10)
        c = MyClassC(self.k) #To pass variable k to class MyClassC

class MyClassC(object):
    def __init__(self,passedVar):
        self.p = passedVar + 0.1 # p will contain (the value entry from MyClassB + 0.1)

h = MyClassA()
h.function1()