Python3中涉及类的继承时,利用可选实参实现__init__方法的多态性
class TestDefault():
def __init__(self, username, password=''):
self.username=username
if password == '':
self.password='********'
else:
self.password=password
def display(self):
print("username:"+self.username+"\npassword:"+self.password)
class TestDefaultInherit(TestDefault):
def __init__(self,username,tel,password=''):
if password == '':
super().__init__(username)
else:
super().__init__(username,password)
self.tel=tel
def display(self):
print("username:"+self.username+"\npassword:"+self.password+"\ntel:"+self.tel)
try:
test_father=TestDefault('zwm')
test_father.display()
test_father = TestDefault('zwm','88888888')
test_father.display()
test_child=TestDefaultInherit('zwm','18021215909','88888888')
test_child.display()
test_child=TestDefaultInherit('zwm','18021215909')
test_child.display()
except TypeError:
print("出现异常!")
else:
print("执行完毕,未发现异常!")