class类中self的作用

拿计算三角形面积举例

# 三角形面积
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值