Classes in Python

Hello,

Apologies if this a basic question. I’m quite new to programming. I just finished working through this exercise and want to confirm that my understanding is correct.

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)

In the above code snippet, I created a class called Circle with a class variable called pi. I then created a method within the class called area. In order to be able to use the class, I have to instantiate it by running circle = Circle(). When I run pizza_area = circle.area(12/2), I am calling my class and the method within that class. The value in parenthesis is my argument radius from the method divided by 2.

Is my understanding correct? One thing I’m not sure of is for return self.pi * radius **2, why do I have to use self.pi instead of just pi?

Thank you so much!

Your understanding sounds spot on to me! As for self.pi, the reason you use this is because the class variable isn’t actually created until an instance of the class has been created, and it is locked to that class. As such for the class to be able to access the variable, it needs to refer to itself, it’s essentially saying ‘Use the pi value I have in my memory’ as opposed to a global pi variable that may have been declared, see below:

pi = 3

class Circle: 
  pi = 3.14

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

  def print_pi(self):
    print(self.pi)
    print(pi)

circle = Circle()

circle.print_pi()
# prints 3.14 then prints 3

also as a note, if you run the code without the pi = 3 at the top you get a NameError as it’s searching for a variable that has not been defined.

1 Like

@adamgaffney96 Thank you very much for the quick reply! Your explanation makes sense to me :pray: