python面向对象的三大特性:封装、继承、多态
- 封装是指它能通过创建一个类,并将若干个属性和方法包装在这个类中,程序员只需创建这个类的一个对象便可以调用这些属性和方法。
# 定义一个类
class Person():
def eat(self):
print("吃")
def sleep(self):
print("睡觉")
# 创建一个人的对象p,它可以调用Person类的方法
p = Person()
p.eat()
p.sleep()
- 继承是对多个类而言的,比如B类继承了A类之后,可以调用A类的所有公有属性和公有方法。
class Person():
def eat(self):
print("吃")
def sleep(self):
print("睡觉")
# 创建Person的一个子类Doctor类
class Doctor(Person):
pass
# 创建一个Doctor类的对象d,它可以调用它的父类Person类的方法
d = Doctor()
d.eat()
d.sleep()
- 多态是在继承的基础上,同一个函数被不同的类调用之后有不同的效果。
class Person():
def __init__(self,name):
self.name = name
def eat(self):
print("%s 在吃饭" %(self.name))
def sleep(self):
print("睡觉")
# 创建Person的一个子类Doctor类
class Doctor(Person):
def __init__(self,name):
self.name = name
p = Person("小明")
p.eat() # 返回 “小明 在吃饭”
d = Doctor("小红")
p.eat() # 返回 “小红 在吃饭”
对象d调用了父类Person中的方法eat(),而使用的属性name是在定义对象d是赋予的。