Python日常笔记(16)- 继承

继承

Python面向对象的继承指的是多个类之间所属关系,子类默认继承父类所有方法和属性,并且所有类默认都是继承object类,object是顶级类,其它类都叫做派生类.

继承有单继承和多继承
单继承:表示某一个类继承一个单一的类叫做单继承
多继承:表示某一个类可以同时继承多个父类叫做多继承,但是当一个类继承多个父类的时候,默认使用从左到右使用第一个父类的同名属性和方法

单继承实例

# 父类
class Parent(object):
   def __init__(self):
       self.number = 1

   def print_info(self):
       print(self.number)

# 子类继承父类
class Children(Parent):
   pass

children = Children()
children.print_info()


需要注意圆括号中基类的顺序,若是基类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找基类中是否包含方法。

多继承

实例

# 父类
class Parent1(object):
   def __init__(self):
       self.number = 1
   def print_info(self):
       print(self.number)
# 父类
class Parent2(object):
   def __init__(self):
       self.number = 2

   def print_info(self):
       print(self.number)
# 子类继承父类
class Children(Parent2, Parent1):
   pass
children = Children()
children.print_info()

注意:当一个类继承多个父类的时候,默认使用从左到右使用第一个父类的同名属性和方法

重写

子类重写父类方法和属性时,调用是都是直接调用子类中重写的属性和方法
实例:

# 子类继承父类Parent2, Parent1
class Children(Parent2, Parent1):
   def __init__(self):
       # 重写父类中的属性
       self.number = 3

   # 重写父类中的方法
   def print_info(self):
       print(f"子类中的方法{self.number}")

mro

使用子类的类名调用__mro__方法查询继承关系

print(Children.__mro__)

多层继承以及super

# 父类1
class Parent1(object):
   def __init__(self):
       self.number = 1
   def print_info(self):
       print(f"Parent1中的print_info方法调用{self.number}")
# 父类2
class Parent2(Parent1):
   def __init__(self):
       self.number = 2
   def print_info(self):
       print(f"Parent2中的print_info方法调用{self.number}")
       super().__init__()
       super().print_info()
# 子类继承父类Parent2, Parent1
class Children(Parent2):
   def __init__(self):
       # 重写父类中的属性
       self.number = 3
   # 重写父类中的方法
   def print_info(self):
       print(f"Children中的print_info方法调用{self.number}")
       super().__init__()
       super().print_info()
children = Children()
children.print_info()


私有方法和私有属性的定义以及修改和获取
举例:

class Sutdent():
   # 私有属性
   __number = 0
   def __init__(self):
       pass
   def getNumber(self):
       return self.__number
   # 修改私有属性值
   def setNumber(self, number):
       self.__func_Number(number)
   # 私有方法
   def __func_Number(self, number):
       self.__number = number
student = Sutdent()
student.setNumber(3)
print(student.getNumber())

作者:阿超
原创公众号:『Python日常笔记』,专注于 Python爬虫等技术栈和有益的程序人生,会将一些平时的日常笔记都慢慢整理起来,也期待你的关注和阿超一起学习,公众号回复【csdn】优质资源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值