ansa_python学习贴2(求解释)
import mathclass Point:
"""A class that stores the x,y,z coordinates of a a point,
with a method that calculates the distance from the origin and
a method that prints the description of the class"""
def __init__(self, x_coord, y_coord, z_coord):
"""This is the constructor of the class"""
self.x = x_coord
self.y = y_coord
self.z = z_coord
def distFromOrigin(self):
"""Method that calculates the distancefrom the origin"""
dist = math.sqrt(self.x**2 + self.y**2 + self.z**2)
return dist
def __repr__(self):
return 'A point with X: '+str(self.x)+' Y: '+str(self.y)+' Z'+ str(self.x)
def main():
myPoint = Point(100.57, 786.46, 436.89)
print(myPoint.x)
myPoint.x = 120.74
distance = myPoint.distFromOrigin()
print('The distance from the origin is: '+str(distance))
#In order to print the description of the object
print(myPoint) #This will print the return of the __repr__
直接运行好像不行,有没有大神指导下,是程序有问题,还是我运行方式不对?
帮助手册错误实在是太多了。 类里面的函数应该缩进吧,另外我觉得注释方法也有问题,反正去掉这两个问题之后,是没有问题的。我也刚学这个 蓝桥承影 发表于 2015-1-10 15:36
类里面的函数应该缩进吧,另外我觉得注释方法也有问题,反正去掉这两个问题之后,是没有问题的。我也刚学这 ...
多谢蓝桥承影的回答,你说的太对了:handshake,类里面的函数需要缩进,谢谢!
修改后成了:
import math
class Point:
"""A class that stores the x,y,z coordinates of a a point,
with a method that calculates the distance from the origin and
a method that prints the description of the class"""
def __init__(self, x_coord, y_coord, z_coord):
"""This is the constructor of the class"""
self.x = x_coord
self.y = y_coord
self.z = z_coord
def distFromOrigin(self):
"""Method that calculates the distancefrom the origin"""
dist = math.sqrt(self.x**2 + self.y**2 + self.z**2)
return dist
def __repr__(self):
return 'A point with X: '+str(self.x)+' Y: '+str(self.y)+' Z'+ str(self.x)
def main():
myPoint = Point(100.57, 786.46, 436.89) #creation of class instance myPoint
print(myPoint.x) #access the value of attribute x
myPoint.x = 120.74 #assign new value
distance = myPoint.distFromOrigin()
print('The distance from the origin is: '+str(distance))
#In order to print the description of the object
print(myPoint) #This will print the return of the __repr__
运行:
main()
结果:
100.57
The distance from the origin is: 907.7281263131599
A point with X: 120.74 Y: 786.46 Z120.74 更正一个小错误:
return 'A point with X: '+str(self.x)+' Y: '+str(self.y)+' Z'+ str(self.x),把x改成z:
return 'A point with X: '+str(self.x)+' Y: '+str(self.y)+' Z'+ str(self.z)
这样运行结果A point with X: 120.74 Y: 786.46 Z436.89 yijianluo 发表于 2015-1-12 09:26
多谢蓝桥承影的回答,你说的太对了,类里面的函数需要缩进,谢谢!
修改后成了:
import math
建议单行注释都以#开始 个人意见,仅供参考:
为啥你的语句都没有分号等分隔行符呢?
这样是否容易出问题啊?
还有缩进的问题,的却经常导致程序不能正确运行。
页:
[1]