Skip to main content

Python 中的函数

函数是用于执行某项特定任务并能够纳入更大的程序的已定义功能。

在 ArcPy 中,所有地理处理工具均作为函数提供,但并非所有函数都是地理处理工具。 除了工具外,ArcPy 还提供多种函数来执行各种任务,如列出特定数据集检索数据集属性,以及在将表名添加到地理数据库前验证表名

请参见 ArcPy 函数概览以了解更多 ArcPy 函数。

函数的常规形式类似于工具;它接受某些必要或不必要的参数,并返回一些内容。 非工具函数的返回值可以有多种形式:从字符串到地理处理对象。 工具函数将始终返回一个 Result 对象并提供地理处理消息

以下示例使用两个 ArcPy 函数,GetParameterAsText 用于接收输入参数,Exists 用于确定输入是否存在。 Exists 函数返回一个布尔值(True 或 False)。

import arcpy
input = arcpy.GetParameterAsText(0)
if arcpy.Exists(input):
 print("Data exists")
else:
 print("Data does not exist")

以下示例使用 ListFeatureClasses 函数创建一个要素类列表,然后遍历该列表,使用边界要素类裁剪每个单独的要素类。

import arcpy
import os
# The workspace environment needs to be set before ListFeatureClasses
# to identify which workspace the list will be based on
arcpy.env.workspace = r"c:\data"
out_workspace = r"c:\data\results"
clip_features = r"c:\data\testarea\boundary.shp"
# Loop through a list of feature classes in the workspace
for fc in arcpy.ListFeatureClasses():
 # Set the output name to be the same as the input name, and
 # locate in the 'out_workspace' workspace
 output = os.path.join(out_workspace, fc)
 # Clip each input feature class in the list
 arcpy.analysis.Clip(fc, clip_features, output, 0.1)