0

I'm attempting to figure out the output from the python program below. 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? My prediction for the result of this program was as follows:

Clowning around now.

Create a Bozo from 3

Create a Bozo from 4

Clown 3

18

3 + 6 = return 9

Clown 4

32

4 + 8 = return 12

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

But the output / answer is:

Clowning around now.

Create a Bozo from: 3

Create a Bozo from: 4

Clown 2

12

Clown 8

64

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()

2 Answers 2

1
# 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)
Sign up to request clarification or add additional context in comments.

3 Comments

@cricket why is c1.value = 6? and does x = 2 because print(c2.clown(c1.clown(2)) ?
@user35 because c1 = Bozo(3)... Multiply 3 by 2. X equals 2 (the first time) because that's the parameter to the clown function
@user3574939 You probably haven't get the difference between instantiating a new object verus a genral function call. When you call c1=Bozo(3), you are creating a new object of Bozo class, and the method __init__() will be called to do some initializing stuff(assigning value = 2 * input). While clown() is a class method. And by chaining the function calls, they will get executed from inside to out.
1

Inside out...

c1.clown(2) runs and returns before anything.

It prints Clown 2, then 2 * c1.value = 2 * 6 = 12

That returns 2 + c1.value = 2 + 6 = 8 , which is passed to c2.clown()

4 + 8 is never ran. It's 8 + 8 because the clown value is multiplied by 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.