类和对象
2020-04-02 本文已影响0人
拼了老命在学习
继承
子代能继承父代所有属性,子代定义的属性与父代相同则会覆盖掉父代属性
class base1:
def __init__(self): # 构造函数 _init_(self,parama....)第一个参数默认没有
self.name = "jerry"
def love(self):
print("%s\n" %self.name)
class base2(base1):
pass
class base3(base1): #可继承多个父类
def __init__(self):
super().__init__() #继承父类同类型属性,防止被子代覆盖
self.words = "like tom" #添加自身属性
def language(self):
print(self.name + " " + self.words)
base = base3()
base.language()
修改部分
class base1:
def __init__(self,name):
self.name = name
def love(self):
print("%s\n" %self.name)
class base2(base1):
pass
class base3(base1):
def __init__(self,name):
super().__init__(name)
self.words = "like tom"
def language(self):
print(self.name + " " + self.words)
name = str(input("请输入\n"))
p = base3(name)
p.language()
拾遗
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class pool:
def __init__(self,x,y):
self.turtle = Turtle(x) #类的实例化
self.fish = Fish(y)
def print_num(self):
print("有%d只乌龟,%d只鱼\n" %(self.turtle.num,self.fish.num))
p = pool(40,400)
p.print_num()