gpt4 book ai didi

Python:AttributeError: 'Point'对象没有属性 'x'

转载 作者:行者123 更新时间:2023-11-30 23:13:37 24 4
gpt4 key购买 nike

Traceback (most recent call last):
line 56, in <module>
distanceToOne = point1.Distance(pointUser)
line 22, in Distance
distance = math.sqrt((self.__x - toPoint.x)**2 +(self.__y - toPoint.y)**2 +(self.__z - toPoint.z)**2)
AttributeError: 'Point' object has no attribute 'x'

出于某种原因,每当我获取三个点来计算距离后,每当我到达:distanceToOne = point1.Distance(pointUser) 时,我都会收到上述错误消息。

如果需要的话,这里有一个更好的 View :http://pastie.org/private/vige6oaphkwestdemr5uw

预先感谢您的帮助!

import math
class Point(object):
def __init__(self, x = 0, y = 0, z = 0, description = 'TBD'):
self.__x = x
self.__y = y
self.__z = z
self.__description = description

def SetPoint(self, coords):
self.__x = coords[0]
self.__y = coords[1]
self.__z = coords[2]

def GetPoint(self):
return [self.__x, self.__y, self.__z]
PointCoords = property(GetPoint, SetPoint)

def Distance(self, toPoint):
toPoint.PointCoords[0]
toPoint.PointCoords[1]
toPoint.PointCoords[2]
return math.sqrt(
(self.__x - toPoint.x)**2 +
(self.__y - toPoint.y)**2 +
(self.__z - toPoint.z)**2)

def SetDescription(self, description):
self.__description = description

def GetDescription(self):
return self.__description
PointDescription = property(GetDescription, SetDescription)

if __name__ == "__main__":
print "Program 9: Demonstrate how to define a class"

point2 = Point()
point1 = Point(10, 54, 788, 'Ploto')
point2.PointCoords = 77, 2, 205
point2.PointDescription = 'Mars'
doAnother = "y"
while(doAnother == "y"):
pointX = raw_input("Enter a X Number: ")
pointY = raw_input("Enter a Y Number: ")
pointZ = raw_input("Enter a Z Number: ")

# Constructor - Represent the user's location
pointUser = Point(pointX, pointY, pointZ, 'Sun')

distanceToOne = point1.Distance(pointUser)
distanceToTwo = point2.Distance(pointUser)

# Comparing the two distances between the two to see which one is the closest
if (distanceToOne > distanceToTwo):
closest = point2
else:
closest = point1
print ('You are closest to',closest.PointDescription(), 'which is located at ',closest.PointCoords())
doAnother = raw_input("Do another (y/n)? ").lower()
print ('Good Bye!')

最佳答案

实际错误是由于访问 toPoint.x 造成的,该文件不存在,因为您从未定义过它。

相关说明,在属性前面添加双下划线会激活 python name mangling特征。实际属性仍可在类外部的 my_point._Point__xmy_point._Point__y 等处公开访问。

就风格而言,在这种情况下似乎没有任何理由使用名称修饰。此功能的预期用例是避免与继承的类发生冲突,它并不是真正尝试创建“私有(private)”变量(为此,约定是使用单个下划线来指示属性何时为实现细节)。

就你的情况而言,我认为你应该正常命名(和访问)属性 xy 等。在 python 中,我们通常不编写 getters 和类成员的 setter ,除非有特殊要求,因为 Python is not Java

关于Python:AttributeError: 'Point'对象没有属性 'x',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com