0

I recently studied introduction of python. There is an ambiguous point that makes me so confused. I know that passing an immutable objects like string, integer will not change after invoking a function.

However, the book told me that a mutable object such as a class object, the original value of the object is changed if the contents of the object are changed inside the function.

so I am confused with the following check point exercise and the example of book.

example of book:

class Circle:
    def __init__(self, radius = 1):
        self.radius = radius

    def getPerimeter(self):
        return 2 * self.radius * 3.14

    def getArea(self):
        return self.radius * self.radius * 3.14

    def setRadius(self, radius):
        self.radius = radius

def main():
    myCircle = Circle()

    n = 5
    printAreas(myCircle, n)

    print("\nRadius is", myCircle.radius)
    print("n is", n)

def printAreas(c, times):
    print("Radius \t\t Area")
    while times >= 1:
        print(c.radius, "\t\t", c.getArea())
        c.radius +=1
        times -=1

main()

check point exercise:

class Count:
    def __init__(self, count = 0):
        self.count = count

def main():
    c = Count()
    n = 1
    m(c,n)

    print("count is", c.count)
    print("n is", n)

def m(c,n):
    c = Count(5)
    n = 3


main()

I wonder that why c.count is same as 0 instead of 5. Thanks all.

chipoyu
  • 1
  • 1
  • `c = Count(5)` doesn't *mutate the existing object `c`*, it overwrites the local name `c` with an entirely new object. And that isn't seen by the function caller the same way that `n = 3` isn't seen. The difference isn't in whether you're *passing* mutable or immutable objects, it's whether you *mutate* them or not. – deceze Jul 27 '22 at 10:27
  • You are not modifying the object in the function, but instantiating a new one each time function m is called, initializing its attribute count as 5 every time. – Nastor Jul 27 '22 at 10:28
  • Because you are creating a new instance of Count in the function and not modifying its value, change it to c.count = 5 in the function – Axeltherabbit Jul 27 '22 at 10:28

0 Answers0