======================添加方法======================
1.添加方法
直接在子类中声明新的方法
2.重写方法
在子类中重新实现父类的方法 - 完全重写
保留父类的功能在子类中添加新的功能 - 部分重写(在子类方法中通过'super().'的方式调用父类方法)
3.类中函数的调用过程
回到函数声明的位置:先看当前类中是否有方法,如果有就直接调用当前类中的方法;没有就去看父类中有没有这个方法;
如果父类中也没有就看父类的父类中有没有....直到找到object类,如果object中也没有就报错!
=====================添加属性======================
1.类的字段
直接在子类中声明新的字段
class Person(object):
num = 61
def __init__(self,name='zhangsan', age=0, sex='男'):
self.name = name
self.age = age
self.sex = sex
self.__face = 60
def eat(self, food):
print('%s在吃%s' % (self.name, food))
@classmethod
def show_num(cls):
print('人类的数量:%d' % cls.num)
class Student(Person):
num2 = 100
# 添加方法
def study(self):
print('%s在写代码' % self.name)
@classmethod
def func1(cls):
print('我是学生类的类方法')
@staticmethod
def func2():
print('我是学生类的静态方法')
@classmethod
def show_num(cls):
print('学生数量:%d' % cls.num)
def eat(self, food):
super().eat(food)
print('吃饱了')
def main():
p1 = Person('张三')
stu1 = Student('李四')
stu1.study()
Student.func1()
# 子类可以使用父类的属性和方法,但是父类不能使用子类中添加的属性和方法
# Person.func2()
Person.show_num()
Student.show_num()
stu1.eat('包子')
print(Student.num2)
网友评论