Why does an instance need to be set to a variable?

About this exercise Instantiation - can somebody explain?
“Above, we created an object by adding parentheses to the name of the class. We then assigned that new instance to the variable cool_instance for safe-keeping.”

If we create an object without assigning it to a variable (just adding parentheses to a class name), is it not safe enough? Safe from what? What are “the dangers”?
Thank you in advance

I think safe-keeping just means a place where we can access it again

If we just make an instance:

CoolClass()

without the variable, there is no way to access the instance

Thank you for the answer, but I still can’t understand, if we “managed” to access it once(during the assignment to a variable), why could not we do this again? In other words - if we change where possible the names of the variables to just class names with parenthesis - will it work? If not, why?(In some cases it worked, I tried)

Code samples of this would be really useful to understand exactly what you did.

How do we then access properties of the instance?

Please, believe, I feel stupid enough, but I NEED to get it. Here is what I meant from exercise Methods with Arguments:
If instead

class Circle:
  pi = 3.14
  def area(self, radius):
    return self.pi*radius**2
circle = Circle()  
pizza_area = circle.area(12/2)
teaching_table_area = circle.area(36/2)
round_room_area = circle.area(11460/2)

we write

class Circle:
  pi = 3.14
  def area(self, radius):
    return self.pi*radius**2
#circle = Circle()  ------  > without this
pizza_area = Circle().area(12/2)
teaching_table_area = Circle().area(36/2)
round_room_area = Circle().area(11460/2)

i changed the code a bit:

from math import pi

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

    def area(self):
        return self.pi*self.radius**2

    def circumference(self):
        return 2 * pi * self.radius

    def diameter(self):
        return self.radius * 2

circle = Circle(6)
print(circle.area())
print(circle.circumference())
print(circle.diameter())

if we now where to follow your approach, we could create a new circle for every method we want to call. Which we would violate DRY (don’t repeat yourself)

i realize this example still isn’t ideal, classes really becomes clear when the project/code base starts to grow, classes give us the capability to group similar code.

1 Like