学习笔记:python中的类(__init__,self,继承)

( 一 )  __init__:

例如我们定义一个Box类,有width, height, depth三个属性,以及计算体积的方法:

class Box:
    def setDimension(self, width, height, depth):
        self.width = width
        self.height = height
        self.depth = depth
 
    def getVolume(self):
        return self.width * self.height * self.depth

b = Box()
b.setDimension(10, 20, 30)
print(b.getVolume())

————————————————
版权声明:本文为CSDN博主「luzhan66」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/luzhan66/article/details/82822896

此时Box的三个属性需要通过函数setDimension输入,而加入__init__的方法,可直接声明width, height, depth为Box的属性,如下:

class Box:

    def __init__(self, width, height, depth):
        self.width = width
        self.height = height
        self.depth = depth
 
    def getVolume(self):
        return self.width * self.height * self.depth
 
b = Box(10, 20, 30)
print(b.getVolume())

————————————————
版权声明:本文为CSDN博主「luzhan66」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/luzhan66/article/details/82822896

( 二 )  self:

     和普通函数相比,在类中定义的函数不同点在于,第一个参数永远是实例变量self。调用时,不用传递该参数。

( 三 )  继承:

    编写类时,总是要从空白开始。如果要编写的类是另一个现成类的特殊版本,则可以使用继承。

原有的类称为父类,而新的类称为子类。

class Box:

    def __init__(self, width, height, depth):
        self.width = width
        self.height = height
        self.depth = depth
 
    def getVolume(self):
        return self.width * self.height * self.depth
##########################################################
class BlackBox(Box):                             #括号里为需继承的父类

    def __init__(self, width, height, depth):    #子类的属性声明
        super().__init__(width, height, depth)   #继承父类各属性
    
    def getVolume(self):
        return self.width * self.height * self.depth

b = BlackBox(10, 20, 30)
print(b.getVolume())

 

 

本人为正在学习python的小白,写文章只是为了加深自己的理解,很多用语不规范,仅供参考。
引用参考:
原文链接:https://blog.csdn.net/luzhan66/article/details/82822896

原文链接:https://blog.csdn.net/fisherming/article/details/93468969

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值