( 一 ) __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