一、父类方法 """ Author:Zhou Create_Date:2022年06月13日--21:52 Tool:PyCharm Software: PyCharm """ """ 类练习题 """ class User: def __init__(self, first_name, last_name, age, favorite): """初始化属性""" self.first_nam
一、父类方法
"""Author:Zhou
Create_Date:2022年06月13日--21:52
Tool:PyCharm
Software: PyCharm
"""
"""
类练习题
"""
class User:
def __init__(self, first_name, last_name, age, favorite):
"""初始化属性"""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.favorite = favorite
# 指定默认值
self.country = "中国"
self.login_attempts = 0
def describe_user(self):
print("当前用户信息:")
print(f"姓:{self.first_name}\t名:{self.last_name}\t年龄:{self.age}\t爱好:{self.favorite}\t国家:{self.country}")
def greet_user(self):
full_name = self.first_name + self.last_name
print("欢迎" + full_name + "你的到来!")
def increment_login(self):
"""登录次数递增"""
self.login_attempts += 1
print(f'当前用户登录次数:{self.login_attempts}')
def reset_login_attempts(self):
"""重置登录次数"""
self.login_attempts = 0
print(f'当前用户登录次数:{self.login_attempts}')
if __name__ == '__main__':
new_person1 = User('周', '文王', '29', '篮球')
new_person1.describe_user()
# 直接修改属性的值(还有一种是通过方法修改属性的值)
new_person1.age = 28
new_person1.describe_user()
new_person1.increment_login()
new_person1.increment_login()
new_person1.reset_login_attempts()
二、子类(初始化父类属性,重写父类方法、增加属性)
"""Author:Zhou
Create_Date:2022年06月13日--22:47
Tool:PyCharm
Software: PyCharm
"""
from User import User
class Admin(User):
def __init__(self, first_name, last_name, age, favorite):
"""初始化父类的属性"""
super().__init__(first_name, last_name, age, favorite)
"""子类特有的属性"""
self.privileges = "游客权限"
def show_privileges(self):
full_name = self.first_name+self.last_name
print(full_name+f"的权限是:{self.privileges}")
person = Admin('周', '文王', '29', '篮球')
person.describe_user()
person.show_privileges()