1. 面向对象的三大特征:封装(提高程序的安全性)、继承(提高代码的复用性)、多态(提高程序的可扩展性和可维护性)
2.封装:
class Student:
def __init__(self,name,age):
self.name=name;
self.__age=age;#不希望在类的外部使用,所以加了两个__
def show(self):
print(self.name,self.__age)
stu=Student("张三",20)
stu.show()
print(stu.name)
#print(stu.__age)
#print(dir(stu))
print(stu._Student__age) #强行操作
3.继承:如果一个类没有继承任何类,则默认继承object ;python支撑多继承
class Person: #person继承object类
def __init__(self,name,age):
self.name=name
self.age=age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self, name, age,stu_no):
super().__init__(name,age)
self.stu_no=stu_no
class Teacher(Person):
def __init__(self, name, age,teachofyear):
super().__init__(name,age)
self.teachofyear=teachofyear
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
teacher.info()
4.方法重写:子类对继承父类的某个属性或方法不满意,重写一个方法 super().xxx()调用父类中被重写的方法
class Person: #person继承object类
def __init__(self,name,age):
self.name=name
self.age=age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self, name, age,stu_no):
super().__init__(name,age)
self.stu_no=stu_no
def info(self):
super().info()
print('学号:',self.stu_no)
class Teacher(Person):
def __init__(self, name, age,teachofyear):
super().__init__(name,age)
self.teachofyear=teachofyear
def info(self):
super().info()
print("教龄:", self.teachofyear)
stu=Student("张三",20,"1001")
teacher=Teacher("李四",34,10)
stu.info()
teacher.info()
5.object:
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):#用于返回一个对于对象的描述
return'我的名字是{0},今年{1}岁'.format(self.name,self.age)
stu=Student("张三",20)
print(dir(stu)) #查看指定对象的属性
print(stu)
print(type(stu))
6.多态:即便不知道一个变量所应用的对象到底是什么类型,任然可以通过这个变量调用方法,在运行过程中更具变量所应用的对象的类型,动态决定调用那个对象中的方法
class animal(object):
def eat(self):
print("动物会吃")
class dog(animal):
def eat(self):
print("狗吃骨头")
class person:
def eat(self):
print("人吃五谷杂粮")
def fun(animal):#定义一个函数
animal.eat()
fun(animal())
fun(dog())
fun(person())
print("--------------")
7.特殊属性和特殊方法:
class A:
pass
class B:
pass
class C(A,B):
def __init__(self,name,age):
self.name=name
self.age=age
x=C('jack',20)
print(x,__doc__) #实例对象的属性字典
# print(C,__dict__) #类对象的属性字典
# print(x,__class__) #输出了对象所属的类
# print(C,__bases__) #c类父类类型的元素
# print(C.__mro__ro) #类的层次结构
#类的方法:
a=100
b=50
d=a.__add__(b) #a+b
print(d)
lst=[11,22,33]
print(lst.__len__()) #lst的长度



