Python成长笔记 - 基础篇 (七)python面向对象

时间:2021-04-09 17:46:02
 
三大特性:
1、封装:在类中对数据赋值、内部调用对外部用户是透明的,这使类变成了一个胶囊或容器,里面包含着类的数据和方法
2、继承:一个类可以派生出子类,在父类中定义的属性、方法会自动被子类继承
# class People:#经典类
class People(object):#新式类
def __init__(self,,age):
self.name = self.age = age
 
def eat(self):
print('%s is eating' %self.name)
 
def work(self):
print("%s is work hard"%self.name )
 
 
class Man(People): #子类继承People父类
def __init__(self,name,age,sex):
#People.__init__(self, name, age)
super(Man, self).__init__(name, age)#新式
self.sex = sex
 
def drink(self):
print("%s is drinking"%self.sex)
 
class Woman(People):
def get_brith(self):
print("%s is get" % self.name)
 
def eat(self):
People.eat(self)
 
 
m1 = Man("mmmmm",23,"男")
m1.eat()
m1.drink()
 
w1 =Woman("wwwww",22)
w1.get_brith()
w1.eat()# class People:#经典类
class People(object):#新式类
def __init__(self,,age):
self.name = self.age = age
 
def eat(self):
print('%s is eating' %self.name)
 
def work(self):
print("%s is work hard"%self.name )
 
 
class Man(People): #子类继承People父类
def __init__(self,name,age,sex):
#People.__init__(self, name, age)
super(Man, self).__init__(name, age)#新式
self.sex = sex
 
def drink(self):
print("%s is drinking"%self.sex)
 
class Woman(People):
def get_brith(self):
print("%s is get" % self.name)
 
def eat(self):
People.eat(self)
 
 
m1 = Man("mmmmm",23,"男")
m1.eat()
m1.drink()
 
w1 =Woman("wwwww",22)
w1.get_brith()
w1.eat()
 
3、多态:一种接口,多种实现
作用:接口重用
 
 
 
 
 
 
语法:
调用函数-->
 
方法
构造方法
析构方法:与构造函数正好相反,在实例释放、销毁的时候自动执行,通常用于做一些收尾工作,例如:关闭数据库链接或关闭一些临时文件
 
私有方法:def __eat():
 
 
 
两种查询策略;
广度优先:python 3.x python 2.x的新式类
深度优先:python 2.x 经典类是按深度优先的查询策略