使用类查找矩形面积的 Python 程序
当需要使用类查找矩形的面积时,使用面向对象的的方法。在这里,定义了一个类,并定义了属性。在类中定义了执行某些操作的函数。创建了类的实例,并使用这些函数查找矩形的面积。
下面是对此的演示 -
示例
class shape_rectangle():
def __init__(self,my_length, my_breadth):
self.length = my_length
self.breadth = my_breadth
def calculate_area(self):
return self.length*self.breadth
len_val = 6
bread_val = 45
print("The length of the rectangle is : ")
print(len_val)
print("The breadth of the rectangle is : ")
print(bread_val)
my_instance = shape_rectangle(len_val,bread_val)
print("The area of the rectangle : ")
print(my_instance.calculate_area())
print()输出
The length of the rectangle is : 6 The breadth of the rectangle is : 45 The area of the rectangle : 270
解释
- 定义了一个名为“shape_rectangle”的类。
- 它具有初始化值的“init”方法。
- 它还有一个方法,用于根据特定参数计算矩形的面积。
- 创建了此类的实例。
- 通过传递所需的参数调用计算面积的函数。
- 它在控制台上显示为输出。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP