Python Circle Class With Getter Setter. In this Python programming tutorial we will learn about the use of Getter and Setter methods. How can we provide a getter and setter method for each variable in a Python class?
What are Getter and Setter Methods in Python class?
A getter method is actually an Accessor Method that returns the value of an instance variable. While a Setter method is also called a Mutator method. It is used to set the value of an instance variable in a Python class.
How to Create Circle Class?
Write a Python program to design a Circle class with radius. Define a constructor, a setter setRadius() and a getter getRadius(). Write down a method to calculate area and the other method for perimeter: findArea() and findPerimeter().
Design the Circle Class
class Circle: ''' Circle class'''
Define constructor for Circle Class
# constructor def __init__(self, radius): self.radius = radius
Writing Accessor and Mutator Methods for radius of Circle
Here we will define getRadius() and setRadius() methods for the instance variable “radius”.
The getRadius () method will return the value of radius.
On the other hand we can set or change the value of radius using setRadius() method. It will take a parameter which will provide the value to the associated instance variable.
# Write getter and setter for radius def setRadius(self,radius): self.radius = radius def getRadius(self): return self.radius
Define Methods To Calculate area and perimeter of Circle
# write findArea() and findPerimeter() def findArea(self): return math.pi * self.radius * self.radius def findPerimeter(self): return 2*math.pi*self.radius
Source code of class Circle with Getter and Setter Methods
Circle object c1 with radius= 4.5 Area = 63.62 Perimeter = 28.27 Circle object c1 with radius= 9.2456 Area = 268.55 Perimeter = 58.09 Second Execution Circle object c1 with radius= 2.54 Area = 20.27 Perimeter = 15.96 Circle object c1 with radius= 5.26 Area = 86.92 Perimeter = 33.05
4,624 total views, 1 views today