user3574939
user3574939

Reputation: 829

Understanding Python Class Output

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

Upvotes: 0

Views: 644

Answers (2)

lincr
lincr

Reputation: 1653

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

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191743

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

Upvotes: 1

Related Questions