Python类
经典类
不由任意内置类型派生出的类,称之为经典类(存在于Python2.0)。
class 类名:
代码
...
新式类
存在于Python3.0以上的类,称之为新式类。
class 类名(object):
代码
...
其中:
object表示的是需要继承的父类,写object或不写参数表示继承的是基类(顶级类)。
面向对象的继承
Python面向对象的继承,指的是多个类之间的所属关系,即子类默认继承父类的所有属性和方法。
所有类默认继承
object
类,**object**
类是顶级类或基类,其他的子类叫作派生类。 ```python父类A
class A(): def init(self):
self.str = "hello world"
def print_info(self):
print(self.str)
子类B
class B(A): pass
result = B() result.print_info() # hello world
<a name="VEq2N"></a>
## 单继承
单继承,指的是**一个类仅继承了一个父类**。
```python
# 父类A
class A():
def __init__(self):
self.str = "hello world"
def print_info(self):
print(self.str)
# 子类B
class B(A):
pass
result = B()
result.print_info() # hello world
多继承
所谓多继承,指的是一个类同时继承了多个父类。
当一个类有多个父类的时候,默认使用的是第一个父类的同名属性和方法。 ```python
父类A
class A(object): def init(self):
self.str = "hello world"
def print_info(self):
print(self.str)
父类B
class B(object): def init(self): self.str = “hi world”
def print_info(self):
print(self.str)
子类C
class C(A, B): pass
result = C() result.print_info() # hello world
<a name="enGhH"></a>
# 子类和父类的方法和属性
<a name="ynTeH"></a>
## 子类重写父类同名方法和属性
**子类和父类具有同名属性和方法时**,**默认使用子类的同名属性和方法**。
```python
# 父类A
class A(object):
def __init__(self):
self.str = "hello world"
def print_info(self):
print(self.str)
# 父类B
class B(object):
def __init__(self):
self.str = "hi world"
def print_info(self):
print(self.str)
# 子类C
class C(A, B):
def __init__(self):
self.str = "I am here!"
def print_info(self):
print(f"哈哈哈,{self.str}")
result = C()
result.print_info() # 哈哈哈,I am here!
__mro__
查看对象的继承关系
print(对象.__mro__)
输出信息:子类 ==> 父类层级,即越靠右,其对应的父级层级越高。
子类调用父类的同名方法
子类调用父类的同名方法和属性:把父类的同名属性和方法再次封装即可。
- 在子类的方法中,如果先调用父类的属性和方法,父类属性会覆盖子类的属性,因此调用子类方法前,先调用子类的属性初始化;
- 调用父类的方法前,为保证调用的是父类的属性,必须在调用方法前调用父类的属性。
——调用谁的方法,就先调用谁的属性。
# 父类A
class A(object):
def __init__(self):
self.str = "hello world"
def print_info(self):
print(self.str)
# 父类B
class B(object):
def __init__(self):
self.str = "hi world"
def print_info(self):
print(self.str)
# 子类C
class C(A, B):
def __init__(self):
self.str = "I am here!"
def print_info(self):
self.__init__() # 先调用子类的属性初始化
print(f"哈哈哈,{self.str}")
# 子类调用父类的同名方法和属性:把父类的同名属性和方法再次封装
def mainA(self):
A.__init__(self) # 先调用父类的属性初始化
A.print_info(self)
def mainB(self):
B.__init__(self) # 先调用父类的属性初始化
B.print_info(self)
result = C()
result.print_info() # 哈哈哈,I am here!
result.mainA() # hello world
result.mainB() # hi world
# print(C.__mro__)
多层继承(单继承)
"""继承方式: A ==> B ==> C ==>D """
# 父类A
class A(object):
def __init__(self):
self.str = "hello world"
def print_info(self):
print(self.str)
# 父类B
class B(object):
def __init__(self):
self.str = "hi world"
def print_info(self):
print(self.str)
# 子类C
class C(A, B):
def __init__(self):
self.str = "I am here!"
def print_info(self):
self.__init__() # 先调用子类的属性初始化
print(f"哈哈哈,{self.str}")
# 子类调用父类的同名方法和属性:把父类的同名属性和方法再次封装
def print_parent(self):
A.__init__(self) # 先调用父类的属性初始化
A.print_info(self)
B.__init__(self) # 先调用父类的属性初始化
B.print_info(self)
class D(C):
pass
result = D() # 孙继承类可以调用多个父级类的方法
result.print_info() # 哈哈哈,I am here!
result.print_parent() # hello world hi world
使用super()
调用父类方法
**super()**
函数可以自动查找父类。调用顺序遵循__mro__
类属性的顺序,比较适合单继承。
# 方法1(Python2):
super(当前类名, 对象或类).xxx
# 方法2(Python3):
super().xxx
其中,第二个参数”对象或类“,一般使用self。
单继承使用super()
"""继承方式: A ==> B ==> C ==> D """
# 父类A
class A(object):
def __init__(self):
self.num = 1
def print_info(self):
print(self.num)
# 父类B
class B(A):
def __init__(self):
self.num = 2
def print_info(self):
print(self.num)
# 调用父级方法
# 方法1:
# super(B, self).__init__()
# super(B, self).print_info()
# 方法2:
super().__init__()
super().print_info()
# 子类C
class C(B):
def __init__(self):
self.num = 3
def print_info(self):
# self.__init__() # 先调用子类的属性初始化
print(self.num)
# 调用父级方法
# 方法1:
# super(C, self).__init__()
# super(C, self).print_info()
# 方法2:
super().__init__()
super().print_info()
class D(C):
pass
result = D() # 孙继承类可以调用多个父级类的方法
result.print_info() # 3 2 1
多继承使用super()
""" 多继承方式----棱形继承
---> B ---
A --| |--> D
---> C ---
"""
class A(object):
def __init__(self):
print("Enter A")
print("Leave A")
class B(A):
def __init__(self):
print("Enter B")
super().__init__()
print("Leave B")
class C(A):
def __init__(self):
print("Enter C")
super().__init__()
print("Leave C")
class D(B, C):
def __init__(self):
print("Enter D")
super().__init__()
print("Leave D")
# 创建对象
d = D() # 创建对象时,自动调用类中的初始化属性
"""
执行结果如下:
Enter D
Enter B
Enter C
Enter A
Leave A
Leave C
Leave B
Leave D
"""
类的私有属性和方法
在Python中,可以为实例属性和方法设置私有权限,即设置某个实例属性或方法不允许子类继承。
私有属性和私有方法只能在同一个类中访问和修改。
class 类名():
# 私有属性
__属性名 = 值
# 私有方法
def __函数名(self):
代码
私有属性和方法示例
```python class A(): def init(self):
self.str = "hello"
self.__money = 100 # 私有属性
def __print_info(self): # 私有方法
print(self.str)
print(self.__money)
class B(A): def init(self): self.str = “world”
def print_info(self):
print("haha")
super().__init__()
super().__print_info()
result = B() result.print_info() # 无法调用私有方法,报错
<a name="rITSi"></a>
## 获取和修改私有属性值
在Python中,**一般定义函数名**`**get_xxx**`**用来获取私有属性,定义**`**set_xxx**`**用来修改私有属性**。
- **私有属性和私有方法只能在同一个类中访问和修改**。
```python
class A():
def __init__(self):
self.str = "hello"
self.__money = 100
def get_money(self): # 获取私有属性
return self.__money
def set_money(self): # 修改私有属性
self.__money = 500
def __print_info(self):
print(self.str)
print(self.__money)
result = A()
print(result.get_money()) # 100
result.set_money()
print(result.get_money()) # 500