欢迎来到python讲堂!打开你的IDE,开始python之旅吧!
init
init是initialize的缩写,就算我们创建实例时,不去引用__init__方法,这里面的命令也会自动执行:
class juice:
ingredient=['oranges','sugar','water']
def __init__(self):
print('orange juice!')
def drink_it(self,how_much):
if how_much=='a little':
print('l need more!')
if how_much=='so much':
print('great!')
orange_juice=juice()
orange_juice.drink_it('a little')
你会得到:
orange juice!
l need more!
虽然我们没有调用init(),但是还是打印出了orange juice!
类的继承(好多品种的果汁!)
果汁当然还有别的口味的,比如苹果汁,西瓜汁之类的,现在我们再来更加一段代码:
class juice:
ingredient = ['oranges','sugar','water']
def drink_it(self,how_much):
if how_much == 'a little':
print('l need more!')
if how_much == 'so much':
print('great!')
class watermelon_juice(juice):
ingredient = ['watermelon','water','sugar']
watermelon = watermelon_juice()
watermelon.drink_it('a little')
你可以看见:l need more!
这里我们看到watermelon_juice这个子类继承了父类也就是juice的所有属性,因此我们在watermelon_juice中调用drink_it不会报错,当然你也可以覆盖(override)
这里我们重写了ingredient,因为西瓜汁和橙子汁配料可不同!
slot
__slot__
是类中不可变的数据:
class slot:
__slot__ = []
完成咯!