Skip to main content

/docs/images/banner.jpg

Python

Constructors

Demonstrate the use of constructors and the init method in a Python class

class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
def perimeter(self):
return 2 * 3.14 * self.radius

circle = Circle(5)
print("Area: ", round(circle.area(),2))
print("Perimeter: ", round(circle.perimeter(),2))

# Output:
# Area: 78.5
# Perimeter: 31.4

note

To compile and run the program, you can use the following commands:

python3 foo.py