拿计算三角形面积举例
# 三角形面积
width = 100
class Triangle:
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
area = self.width * self.height / 2.0 #<-------------------------------
return area
>>> Triangle(4, 5).getArea()
>>> 10.0
# 三角形面积
width = 100
class Triangle:
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
area = width * self.height / 2.0 #<-------------------------------
return area
>>> Triangle(4, 5).getArea()
>>> 250.0
上下两段代码唯一不同的是在计算面积公式的位置,width 这个变量用的是’width‘还是‘self.width’,用self的作用就是限制了width 这个变量只能用传入的参数,与全局的定义无关。这样定义的类就不会轻易被全局变量影响。
当然如果没有相应的参数也可以直接在class里定义,这样有self也会使用class类里的变量,而不是全局变量,如下:
width = 1111
class Triangle:
width = 100
def __init__(self, height):
self.height = height
def getArea(self):
area = self.width * self.height / 2.0
return area
>>> Triangle(4, 5).getArea()
>>> 250.0
上述中虽然‘width’传入了4,但是既没有用传入的4,也没有用全局的1111,而是用了类中定义的100。如果‘init’中定义了‘width’那还是会用传入的参数,如下:
width = 1111
class Triangle:
width = 100
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
area = self.width * self.height / 2.0
return area
>>> Triangle(4, 5).getArea()
>>> 10.0