#python学习笔记
38课__init__方法:构造方法,调用对象,在对象被创建时自动调用
我们可以通过重写这个方法,自定义对象的初始操作
#init(self,)
class Ball:
def __init__(self,name):#可以是多个参数
self.name=name
def kick(self):
print('我是%s,谁踢我'%self.name)
b=Ball('土豆')
b.kick()
39课继承 class DeriveClassName(BaseClassName)
子类中函数名称与继承的父类名称相同。则会自动覆盖父类的属性或方法,调用hello认准的是Child类中定义的hello、
#39课继承源码
class Parent():
def hello(self):
print('父类正在被调用。。。')
class Son(Parent):
pass
class Child(Parent):
def hello(self):
print('子类正在被调用。。。')
#子类中函数名称与继承的父类名称相同。则会自动覆盖父类的属性或方法,调用hello认准的是Child类中定义的hello、
#以下为调用实例
a=Parent()
b=Son()
c=Child()
a.hello()#父类正在被调用。。。
b.hello()#父类正在被调用。。。
c.hello()#子类正在被调用。。。
import random as r
class Fish:
def __init__(self):
self.x=r.randint(0,10)
self.y=r.randint(0,10)
def move(self):
self.x -=1
print('我的位置是:',self.x,self.y)
class Coldfish(Fish):
pass
class Shark(Fish):
def __init__(self):
super(Shark, self).__init__()#super方法 继承父类
self.hungry=True
def eat(self):
if self.hungry:
print('吃吃吃')
self.hungry=False
else:
print('吃饱了')
#以下为调用实例
fish=Fish()
fish.move()
fish.move()
fish.move()
shark=Shark()
shark.eat()
shark.eat()
shark.move()