5.1__init__
#__init__()可以在类里面初始化
class shemale_cai:
def __init__(self):
self.gender='女'
self.age=1
def print_info(self):
print(f'蔡徐坤是一名篮球巨星,性别 {self.gender} 年龄 {self.age}')
caixukun=shemale_cai()
caixukun.print_info()
5.2__init__带参数
class television():
def __init__(self,width,height):
self.width = width
self.height = height
def print_info(self):
print(f'电视机的宽度为{self.width}')
print(f'电视机的高度为{self.height}')
sony=television(30,20)
sony.print_info()
5.3__str__()
class television():
def __init__(self,width,height):
self.width = width
self.height = height
def print_info(self):
print(f'电视机的宽度为{self.width}')
print(f'电视机的高度为{self.height}')
def __str__(self):
return("这是索尼电视机的相关属性")#print(sony)时不输出内存,输出解释说明文字
sony=television(30,20)
sony.print_info()
print(sony)
5.4__del__() 删除
class television():
def __init__(self,width,height):
self.width = width
self.height = height
def print_info(self):
print(f'电视机的宽度为{self.width}')
print(f'电视机的高度为{self.height}')
def __del__(self):
print('对象已经删除')#系统自动调用
sony=television(30,20)
sony.print_info()
5.5 面向对象之继承
#父类
class A(object):
def __init__(self):
self.num=1
def info__print(self):
print(self.num)
#子类
class B(A):
pass
result=B()
result.info__print()
5.6 单继承
class teacher(object):
def __init__(self):
self.subject='数学成绩'
def study_math(self):
print(f'好好学习取得好的{self.subject}')
class student(teacher):
pass
xxx=student()
print(xxx)
xxx.study_math()
5.7 多继承
class math_teacher(object):
def __init__(self):
self.subject='数学成绩'
def study_math(self):
print(f'好好学习取得好的{self.subject}')
class English_teacher(object):
def __init__(self):
self.subject='英语成绩'
def study_English(self):
print(f'好好学习取得好的{self.subject}')
class student(English_teacher,math_teacher):
pass
xxx=student()
print(xxx)
xxx.study_math()
xxx.study_English()#一个类拥有多个父类时,默认使用第一个父类的同名属性和用法
#同样如果子类里面也有和父类相同名字的属性,优先子类