多态;同一个事情有多种形态。同样的方法名,完成不一样的具体方法的实现
# 如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法:
# 多态
class Animal:
"""这是个动物"""
def __init__(self, can_fly=False):
print("调用 __init__() 函数当实例化时!")
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("我可以飞!")
else:
print("我不能飞!")
class Bird(Animal): #和class Animal 对等的写了两个类,并没有继承关系
"""这是鸟类"""
def fly(self):
print("可以飞得更高!")
bird = Bird()
bird.fly() # 可以飞得更高!
#以上叫做重载,
#方法重写:
#如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:
class Parent: # 定义父类
def a(self):
print(‘调用父类方法’)
class Child(Parent): # 定义子类
def b(self):
print('调用子类方法')
c = Child() # 子类实例
c.b() # 子类调用重写方法 --这里已经把父类覆盖重写,执行子类了
super(Child, c).a() # 用子类对象调用父类已被覆盖的方法 super,调出父类
“”"
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,
直接用类名调用父类方法在使用单继承的时候没问题,
但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
“”"
#登入
class Animal:
"""这是一个动物"""
def __init__(self,name):
self.name=name
def fly(self):
print("我可以飞")
def eat(self):
print("模拟吃的方法")
a=Animal("aaa")
a.name()
a.fly() #eat和fly是自己定义的函数名
a.eat() #调用的时候不仅可以调用a方法,也可以调用eat方法,他会自己显示。
print(a.__doc__)
def reg():
username = input("请输入用户名[注册]:")
password = input("请输入密码[注册]:")
if check(username) >= 0:
print("你注册的用户名已经存在。")
else:
print("恭喜你,用户名。")
username.append(username)
password.append(password)
print("恭喜你,注册成功")
def login():
username = input("请输入用户名[登入]:")
password = input("请输入密码[登入]:")
index =check(username)
if index >= 0:
if password[index] == password:
print("恭喜你,登入成功。")
else:
print("抱歉,密码输入错误。")
else:
print("抱歉,登入用户名不存在。")
def check(username):
for i in range(len(username)):
if username[i] == username:
return i
return -1
username = ['hello', 'woniu', 'good']
password = ['111', '222', '333']
reg()
login()