面向对象的特点:封装 继承 多态
class 子类(父类)
继承的特点 class张无忌(张翠山)
- 子类拥有父亲的属性和方法 张无忌 拥有 张翠山的 财产 房产 衣服
- 子类拥有自己的属性和方法 张无忌拥有 教主 老婆
- 子类可以重写 (覆盖、改写)父类的方法 张无忌改进武当剑派
人类 ——男人类 女人类
class People(object):
def __init__(self, name="", age="", sex=""):
self.name = name
self.age = age
self.sex = sex
def eat(self):
print("人类需要细嚼慢咽吃饭")
class Man(People):
def __init__(self, name="", age="", sex="", hu_zi="",):
# super:当前类的父类的对象
# self:当前类的对象
super(Man, self).__init__(name, age, sex)
self.hu_zi = hu_zi
def smoke(self):
print("{}抽烟".format(self.name))
def eat(self):
super(Man, self).eat()
print("{}吃了3碗饭".format(self.name))
m = Man(name="张三", age="20", sex="男", hu_zi="络腮胡")
m.eat()
m.smoke()
什么时候用super?
如果想保留父亲的功能但是又想拓展自己的功能
类方法 和 静态方法
# self:当前类的对象
# super:当前类的父类的对象
# cls:当前类
# 类方法 和 静态方法
class People(object):
count = 0
color = ""
def __init__(self, name="", age=0):
self.name = name
self.age = age
def eat(self):
print("{}正在吃饭".format(self.name))
@classmethod # 类方法 调用形式 类名.方法名()
def log_info(cls):
# cls=class 表示当前类
print("这是类方法-{}".format(cls.count))
@staticmethod # 静态方法, 不需要用self/cls (类和对象都可以打点调用静态方法)
def method():
print("hello world")
People.log_info()
# People.eat() 类名不能调用对象方法/对象属性
People.method()
p = People()
p.meth
练习
1. 在现有代码基础上创建一个男学生类,具备 班级,学号等属性
2. 学生 具备 学习方法
3. 学生需要先吃早饭再细嚼慢咽
4. 学生调用学习方法,输出 ***在学习
"""
class ManStudent(Man):
def __init__(self, name="", age="", sex="", hu_zi="", stu_class="", stu_id=""):
super(ManStudent, self).__init__(name, age, sex, hu_zi)
self.stu_class = stu_class
self.stu_id = stu_id
def study(self):
print("{}在学习".format(self.name))
def eat(self):
print("学生先吃早饭")
super(Man, self).eat()
s = ManStudent(name="李四")
s.eat()
s.study()