属性错误:'int'对象没有属性'x
我知道这个话题在这里很常见,不过我找不到一个真正能帮我解决问题的例子。我正在尝试运行一个脚本,目的是在一个形状文件中添加两个新字段(x 和 y 坐标),然后用代码块中的内容填充这些字段。这是针对 ArcGIS 10.2.2 的,但我觉得问题不在 ArcGIS 本身。下面是我的脚本:
# Add new fields for "New_X" and "New_Y" for new points to be added
# Calculate values for those new fields based on distance along line
import arcpy, arcpy.mapping
from arcpy import env
env.workspace = r"G:\Geocomputation_Project\Section_C\Model_Shapes"
env.overwriteOutput = True
# Set local Variables
in_table = 'Points.shp'
field_x = 'New_X'
field_y = 'New_Y'
expression = "getXY(!Shape!, !ITEMID!, !CHAINAGE!)"
code_block_x = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
pNew = 0
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew+=line.positionAlongLine(pointPos).firstPoint
pNew.X"""
code_block_y = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
pNew = 0
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew+=line.positionAlongLine(pointPos).firstPoint
pNew.Y"""
# Execute AddField for each new X and Y coord
arcpy.AddField_management(in_table, field_x, "Double")
arcpy.AddField_management(in_table, field_y, "Double")
# Execute CalculateField to each new X and Y field
arcpy.CalculateField_management(in_table, field_x, expression, "PYTHON_9.3", code_block_x)
arcpy.CalculateField_management(in_table, field_y, expression, "PYTHON_9.3", code_block_y)
我一直收到一个错误提示:AttributeError: 'int' object has no attribute 'X'。
相关文章:
- 暂无相关问题
2 个回答
0
我明白了,问题不仅仅是语法或缩进错误。还需要把 pNew 这个变量“返回”出去。下面是可以正常运行的脚本:
code_block_x = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew=line.positionAlongLine(pointPos).firstPoint
return pNew.X"""
还有
code_block_y = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew=line.positionAlongLine(pointPos).firstPoint
return pNew.Y"""
0
假设标题中的错误是正确的,而不是帖子正文中的错误,那么你的问题就是:
pNew = 0
# ...
pNew.Y
这应该很明显,这样做是行不通的。