类的相关知识
定义教师类:
class Teacher:
school = ‘偶的博爱‘
# (egon_obj,‘egon‘,18)
def __init__(self, name, age):
self.name = name
# egon_obj.name=‘egon‘ #egon_obj.__dict__[‘name‘]=‘egon‘
self.age = age
# egon_obj.age=18
#teach(egon_obj)
def teach(self):
print(‘%s is teaching‘ %self.name)
def foo(self):
print(‘================================‘)
可以用类实例化出对象
egon_obj = Teacher(‘egon‘, 18) # __init__(egon_obj,‘egon‘,18)
alex_obj = Teacher(‘alex‘, 84) # __init__(alex_obj,‘alex‘,18)
类的属性引用:数据属性+函数属性
print(Teacher.school)
print(Teacher.teach) #函数属性
Teacher.teach() #必须传值
对象的属性引用
print(egon_obj.name,egon_obj.age)
类与对象的名称空间
print(Teacher.__dict__)
继承
class People:
pass
class Animal:
pass
class Student(People,Animal): #people称为基类或父类
pass
print(Student.__bases__)
print(People.__bases__)
print(Animal.__bases__)
在python3中,所有类默认继承object,
但凡是继承了object类的子类,以及该子类的子类,都称为新式类(在python3中所有的类都是新式类)
没有继承object类的子类成为经典类(在python2中,没有继承object的类,以及它的子类,都是经典类)
解决代码的重用的问题,减少代码冗余
继承是一种什么‘是’什么的关系
class People:
def __init__(self, name, age):
# print(‘People.__init__‘)
self.name = name
self.age = age
def walk(self):
print(‘%s is walking‘ %self.name)
class Teacher(People):
pass
class Student(People):
pass
t=Teacher(‘egon‘,18)
print(t.name,t.age)
print(t.__dict__)
t.walk()
s=Student(‘alex‘,13)
print(s.name,s.age)
s.walk()
继承是用来创建新的类得得一种方式,好处是可以减少重复代码
继承是类与类之间的关系。是一种什么是什么的关系
组合: 是一种什么有什么的关系,也是为了减少重复代码
class People:
def __init__(self, name, age, year, mon, day):
self.name = name
self.age = age
self.birth = Date(year, mon, day)
def walk(self):
print(‘%s is walking‘ % self.name)
class Date:
def __init__(self,year,mon,day):
self.year=year
self.mon=mon
self.day=day
def tell_birth(self):
print(‘出生于<%s>年 <%s>月 <%s>日‘ % (self.year,self.mon,self.day))
class Teacher(People):
def __init__(self, name, age, year, mon, day,level,salary):
People.__init__(self,name,age,year,mon,day)
self.level=level
self.salary=salary
def teach(self):
print(‘%s is teaching‘ %self.name)
class Student(People):
def __init__(self, name, age, year, mon, day,group):
People.__init__(self,name,age,year,mon,day)
self.group=group
def study(self):
print(‘%s is studying‘ %self.name)
# t=Teacher(‘egon‘,18,1990,2,33)
# print(t.name,t.age)
# print(t.birth)
# t.birth.tell_birth()
# print(t.birth.year)
# print(t.birth.mon)
# print(t.birth.day)
接口
python中没有接口函数需要用定义类来模拟
class File:#定义接口Interface类来模仿接口的概念,
def read(self): #定接口函数read
pass
def write(self): #定义接口函数write
pass
class Txt(File): #文本,具体实现read和write
def du(self):
print(‘文本数据的读取方法‘)
def xie(self):
print(‘文本数据的读取方法‘)
class Sata(File): #磁盘,具体实现read和write
def read(self):
print(‘硬盘数据的读取方法‘)
def write(self):
print(‘硬盘数据的读取方法‘)
class Process(File):
def read(self):
print(‘进程数据的读取方法‘)
def write(self):
print(‘进程数据的读取方法‘)
父类要限制
1:子类必须要有父类的方法
2:子类实现的方法必须跟父类的方法的名字一样
import abc
class File(metaclass=abc.ABCMeta):
@abc.abstractmethod
def read(self):
pass
@abc.abstractmethod
def write(self):
pass
class Txt(File): #文本,具体实现read和write
def read(self):
pass
def write(self):
pass
t=Txt()