|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import math
- class Point:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def getX(self):
- return self.x
- def getY(self):
- return self.y
- class Line:
- def __init__(self, p1, p2):
- self.x = p1.getX() - p2.getX()
- self.y = p1.getX() - p2.getY()
- #self.AB = math.sqrt((self.x * self.x )+ (self.y * self.y))
- def getLen(self):
- AB = math.sqrt(((self.x)**2 )+ ((self.y)**2) )
- return AB
- #return self.AB
- p1 = Point(1, 1)
- p2 = Point(4, 5)
- line = Line(p1, p2)
- line.getLen()
复制代码
在类和对象这里,感觉自己有点懵。在getLen方法里面,我定义一个AB求得两点之间的距离,但是看小甲鱼老师的答案是self.AB,两者算出来的答案是一样的,那他们有什么区别?
我的理解如果有self,在类定义中所有函数(方法)都可以引用,即相当于类中的全局变量。例如:
- class Line:
- def __init__(self):
- self.ab = 1
- def getLen(self):
- return self.ab
复制代码- >>> a = Line()
- >>> a.getLen()
- 1
复制代码
- class Line:
- def __init__(self):
- ab = 1
- def getLen(self):
- return ab
复制代码- >>> a = Line()
- >>> a.getLen()
- Traceback (most recent call last):
- File "<pyshell#38>", line 1, in <module>
- a.getLen()
- File "D:\py\test2.py", line 5, in getLen
- return ab
- NameError: name 'ab' is not defined
复制代码
|
|