Python学习笔记:2.1.4 继承

本文是学习齐老师的《python全栈工程师》课程的笔记,欢迎学习交流。同时感谢齐老师的精彩传授!

一、课程目标
  • 理解继承的含义
  • 使用继承编写类
二、详情解读

01.OOP的三大特性:

  • 继承(inheritance)
  • 多态(polymorphism)
  • 封装(encapsulation)

02.单继承:

  • 例题1:创建一个关于人的类(Person),再创建关于学生的类(Student),并且Student继承Person类
class P:
	person = 2
class C(P):
	pass
print(C.person) # 2
print(C.__base__) #  表示当前类的父类
print(P.__base__) #  object类是所有类的公共父类(或者叫基类)

# 例子解答:
class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def get_name(self):
		return self.name
	def get_age(self):
		return self.age

class Student(Person):
	def __init__(self, school, name, age):
		self.shool = school
		# Person.__init__(self, name, age)
		super().__init__(name, age)
	def grade(self,n):
		print('{name} is {n} grade.'.format(name=self.name, n=n))

st1 = Student('soochow university', 'Galileo', 27)
st1.grade(9) # Galileo is 9 grade.
print(st1.get_name()) # Galileo
print(st1.get_age()) # 27

03.多继承:

例题2:创建表示子一代继承父母性别染色体的类,并通过随机方法得到子一代的性别

class P1:
	p1 = 1
class P2:
	p2 = 2
class C(P1, P2):
	pass
print(C.p1) # 1
print(C.p2) # 2

class Base:
	def __init__(self):
		print('base')
class A(Base):
	def __init__(self):
		print('a-base')
class B(Base):
	def __init__(self):
		print('b-base')
class CC(A, B):
	def __init__(self):
		print('cc-a-b')
		A.__init__(self)
		B.__init__(self)

cc = CC() # cc-a-b a-base b-base

# 例题讲解:
import random
class Father:
	def __init__(self):
		self.father_chromosome = 'XY'
	def father_do(self):
		print('Make money')
class Mother:
	def __init__(self):
		self.mother_chromosome = 'XX'
	def mother_do(self):
		print('Manage money')
class Child(Father, Mother):
	def __init__(self):
		Father.__init__(self)
		Mother.__init__(self)
	def child_gender(self):
		fat= random.choice(self.father_chromosome)
		mot = random.choice(self.mother_chromosome)
		print('father:', fat, '&', 'mother:', mot)
		chi = fat + mot 
		if 'Y' in chi:
			return 1		
		return 0
p = Child()
if p.child_gender():
	print('is a boy')
else:
	print('is a girl')

注意: 尽量多用单继承而少用多继承

三、课程小结
  • 学习了类的单继承
  • 学习了类的多继承
四、作业

创建类SchoolKid,初始化小孩的姓名、年龄,并且有访问和修改属性的方法。然后创建类ExaggeratingKid,继承SchoolKid,子类中覆盖父类中访问年龄的方法,并将实际年龄增加 2.

class SchoolKid:
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def get_name(self):
		return self.name

	def get_age(self):
		return self.age

	def set_name(self, name):
		self.name = name

	def set_age(self, age):
		self.age = age


class ExaggeratingKid(SchoolKid):

    def __init__(self, name, age):          
          super().__init__(name, age)

    def get_age(self):
      super().set_age(self.age + 2)
      return self.age

kid = ExaggeratingKid('Tom', 18)
age = kid.get_age()
print(age) # 20

你可能感兴趣的:(Python全栈工程师学习笔记,python进阶语法,python继承)