简体   繁体   English

了解Python类输出

[英]Understanding Python Class Output

I'm attempting to figure out the output from the python program below. 我试图找出下面的python程序的输出。 The portion of the program that is most confusing to me is the print statement in main print(c2.clown(c1.clown(2))) what exactly is happening in this line? 程序中最让我感到困惑的部分是主print(c2.clown(c1.clown(2)))的print语句在此行中到底发生了什么? My prediction for the result of this program was as follows: 我对该程序结果的预测如下:

Clowning around now. 现在到处都是。

Create a Bozo from 3 从3创建Bozo

Create a Bozo from 4 从4创建Bozo

Clown 3 小丑3

18 18岁

3 + 6 = return 9 3 + 6 =返回9

Clown 4 小丑4

32 32

4 + 8 = return 12 4 + 8 =返回12

print(c2.clown(c1.clown(2)) = 12 * 2 = 24 ???? print(c2.clown(c1.clown(2))= 12 * 2 = 24 ????

But the output / answer is: 但是输出/答案是:

Clowning around now. 现在到处都是。

Create a Bozo from: 3 从以下位置创建一个Bozo:3

Create a Bozo from: 4 从以下位置创建一个Bozo:4

Clown 2 小丑2

12 12

Clown 8 小丑8

64 64

16 16

 class Bozo:
    def __init__(self, value):
        print("Create a Bozo from:", value)
        self.value = 2 * value


    def clown(self, x):
        print("Clown", x)
        print(x * self.value)
        return x + self.value


def main():
    print("Clowning around now.")
    c1 = Bozo(3)
    c2 = Bozo(4)
    print(c2.clown(c1.clown(2)))

main()
# c1.clown(2) works as :
def clown(self, x):  #x=2, c1.value = 6
    print("Clown", x) #print("Clown, 2")
    print(x * self.value) #print(12) 12=6*2
    return x + self.value #return 2+6=8 

# c2.clown(8) works as :
def clown(self, x):  #x=8, c1.value = 8
    print("Clown", x) #print("Clown, 8")
    print(x * self.value) #print(64) 64=8*8
    return x + self.value #return 8+8=16

print(16)

Inside out... 反了...

c1.clown(2) runs and returns before anything. c1.clown(2)运行并在返回任何内容之前返回。

It prints Clown 2, then 2 * c1.value = 2 * 6 = 12 它显示小丑2,然后2 * c1.value = 2 * 6 = 12

That returns 2 + c1.value = 2 + 6 = 8 , which is passed to c2.clown() 返回2 + c1.value = 2 + 6 = 8 ,该值传递给c2.clown()

4 + 8 is never ran. 4 + 8永远不会运行。 It's 8 + 8 because the clown value is multiplied by 2 这是8 + 8因为小丑值乘以2

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

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