example: class Ball: def __init__(self): self.color = "Blue" self.brand = "Usha" self.cost = 30 ball_object = Ball()# Creating Object of class Ball. # calling instance variable/properties outside the class. print(ball_object.color) print() print(ball_object.brand) print() print(ball_object.cost) print()
Output: Blue Usha 30
Please read all the lines carefully. In the above example, we have created a class called Ball that has some properties defined inside __init__(). Now we will learn what happens when we create an object of a class. As we know our computer memory (RAM) is divided into various sections or blocks and each block is used for a different purpose as shown in figure 1. In figure 1, Code Segment is containing our program/code, Stack Segment contains Local Variables present in our program, Heap Segment contains objects present in our program, and Static Segment contains static variables present in our program code.
Now see our example, In our example, we have created one class named “Ball” that has some properties named “color”, “brand”, “cost” after that, object “ball_object” of a class is created. When we create an object, a block of memory is allocated, the address of the object of a class is stored in a reference variable(ball_object) and starts pointing to that memory location as shown in Figure 2. As we know, python supports dynamic memory allocation so to support dynamic memory allocation python requires heap memory. All the properties of an object are present inside the heap section of memory and the reference variable “ball_object” is present inside the Stack section of the memory as shown in Figure 2. As of now, it is enough. Read more blogs here. Please share and comments.
Contributed By – Devanshu Kumar
Contribute your article – email@example.com