博客
关于我
python基础之--面相对象--OOP基本特性
阅读量:797 次
发布时间:2023-03-07

本文共 6642 字,大约阅读时间需要 22 分钟。

Python基础之–面向对象–OOP基本特性

文章目录

1. OOP基本特性

1.1 封装

封装是将对象的属性和方法包装在一起,对外隐藏实现细节,只提供必要的接口给外部访问。在Python中,通过__init__方法初始化属性,并通过方法来操作这些属性。以__开头的属性或方法是私有的,在子类和类外部无法直接使用,可使用“私有”属性和“公有”方法控制外部访问。

1.2 继承/派生

继承是从已有的类中派生出新的类,新类具有原类的数据属性和行为,并能扩展新的能力。派生类就是从一个已有类中衍生出新类,在新的类上可以添加新的属性和行为。继承/派生的作用是用继承派生机制,可以将一些共有功能加在基类中,实现代码的共享。在不改变基类的代码的基础上改变原有类的功能。继承/派生名词:基类(base class)/超类(super class)/父类(father class),派生类(derived class)/子类(child class)。

1.2.1 基础概念

继承/派生

  • 继承是从已有的类中派生出新的类,新类具有原类的数据属性和行为,并能扩展新的能力。
  • 派生类就是从一个已有类中衍生出新类,在新的类上可以添加新的属性和行为。

继承/派生的作用

  • 用继承派生机制,可以将一些共有功能加在基类中。实现代码的共享。
  • 在不改变基类的代码的基础上改变原有类的功能。

继承/派生名词:

  • 基类(base class)/超类(super class)/父类(father class)
  • 派生类(derived class)/子类(child class)

1.2.3 继承实现

class Father():
def __init__(self):
self.money = 1000
def fn(self):
print("我是父亲的fn方法")
class Mother():
def __init__(self):
self.car = "BYD"
def fm(self):
print("我是母亲的fm方法")
class Son(Father, Mother):
def __init__(self):
Father.__init__(self)
Mother.__init__(self)
self.school = "学校"
s1 = Son()
print(s1.money, s1.car, s1.school)
s1.fn()
s1.fm()

输出结果:

1000 BYD 学校
我是父亲的fn方法
我是母亲的fm方法

1.2.4 覆盖

在子类中实现与基类同名的方法,我们叫覆盖。作用是实现和父类同名,但功能不同的方法。覆盖示例:

class Animal:
x = 1000
def __init__(self, name):
self.name = name
def eat(self):
print("eat")
def sleep(self):
print("sleep")
def run(self):
print("run")
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age
self.x = 6000
def eat(self):
print("Cat.eat")
def sleep(self):
print("Cat.sleep")
def run(self):
print("Cat.run")
c1 = Cat("小花", 3)
print(c1.x)
print(c1.name)
print(c1.age)
c1.eat()
c1.sleep()
c1.run()

输出结果:

6000 小花 3
Cat.eat
Cat.sleep
Cat.run

2. 多态

多态是指同一个方法在不同对象上具有不同的行为。通过多态,可以使得不同类型的对象以相同的接口表现出不同的行为。多态的实现通常通过继承和方法重写来实现。

多态示例:

class Animal():
def run(self):
print('动物在奔跑')
class Dog(Animal):
def run(self):
print('狗在奔跑')
def dog_eat(self):
print('狗在吃东西')
class Cat(Animal):
def run(self):
print('猫在奔跑')
def cat_eat(self):
print('猫在吃东西')
class Fish(Animal):
def youyong(self):
print('鱼在游动')
def fn(animal):
if isinstance(animal, Animal):
animal.run()
dig = Dog()
cat = Cat()
fish = Fish()
fn(dig)
fn(cat)
fn(fish)
print(isinstance(dig, Dog))
print(isinstance(cat, Dog))
print(isinstance(fish, Fish))
print(isinstance(dig, Animal))
print(isinstance(cat, Animal))
print(isinstance(fish, Animal))

输出结果:

狗在奔跑
猫在奔跑
动物在奔跑
True
False
True
True
True

3. 操作对象成员

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
p1 = Person('张三', 20)
print(p1.name, p1.age)
p1.age = 30
p1.money = 1000

访问对象的成员

  • 取值操作:p1.age
  • 存值操作:p1.age = 30

4. 私有属性

class Person:
__x = 100
def __init__(self):
self.__y = 30
def fn(self):
print("私有属性", self.__x)
print("私有属性", self.__y)
def tool(self):
self.__x = 666
self.__y = 666
p1 = Person()
print(p1.__x) # 私有属性不能在类外面直接访问
print(p1.__y)
p1.fn()
p1.tool()
p1.fn()

输出结果:

私有属性 100
私有属性 30
私有属性 666
私有属性 666

5. 重写

魔术方法

运算符重载是指让自定义的类生成的对象(实例)能够使用运算符进行操作。运算符重载的作用是让自定义类的实例像内建对象一样进行运算符操作,让程序简洁易读,对自定义对象将运算符赋予新的运算规则。运算符重载说明:运算符重载方法的参数已经有固定的含义,不建议改变原有的意义。

运算符重载表格: | 方法名 | 运算符和表达式 | 说明 | |------------------|----------------|------| | __add__(self, rhs) | self + rhs | 加法 | | __sub__(self, rhs) | self - rhs | 减法 | | __mul__(self, rhs) | self * rhs | 乘法 | | __truediv__(self, rhs) | self / rhs | 除法 | | __floordiv__(self, rhs) | self // rhs | 地板除 | | __mod__(self, rhs) | self % rhs | 取模(求余) | | __pow__(self, rhs) | self ** rhs | 幂 | | __str__(self) | str(self) | 定义对象的字符串表示 |

Box类实现:

class Box:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def __add__(self, other):
new_length = self.length + other.length
new_width = self.width + other.width
new_height = self.height + other.height
return Box(new_length, new_width, new_height)
def __sub__(self, other):
new_length = self.length - other.length
new_width = self.width - other.width
new_height = self.height - other.height
return Box(new_length, new_width, new_height)
def __mul__(self, scalar):
new_length = self.length * scalar
new_width = self.width * scalar
new_height = self.height * scalar
return Box(new_length, new_width, new_height)
def __truediv__(self, scalar):
new_length = self.length / scalar
new_width = self.width / scalar
new_height = self.height / scalar
return Box(new_length, new_width, new_height)
def __floordiv__(self, scalar):
new_length = self.length // scalar
new_width = self.width // scalar
new_height = self.height // scalar
return Box(new_length, new_width, new_height)
def __mod__(self, scalar):
new_length = self.length % scalar
new_width = self.width % scalar
new_height = self.height % scalar
return Box(new_length, new_width, new_height)
def __pow__(self, exponent):
new_length = self.length ** exponent
new_width = self.width ** exponent
new_height = self.height ** exponent
return Box(new_length, new_width, new_height)
def __str__(self):
return f"Box(length={self.length}, width={self.width}, height={self.height})"
b1 = Box(1, 2, 3)
print(b1)
print(b1 + b1)
print(b1 - b1)
print(b1 * 2)
print(b1 / 2)
print(b1 // 2)
print(b1 % 2)
print(b1 ** 2)

输出结果:

Box(length=1, width=2, height=3)
Box(length=2, width=4, height=6)
Box(length=0, width=0, height=0)
Box(length=2, width=4, height=6)
Box(length=0.5, width=1.0, height=1.5)
Box(length=0, width=1, height=1)
Box(length=1, width=0, height=1)
Box(length=1, width=4, height=9)

6. super函数

super函数是用于调用父类(超类)的方法。

2.1 基本使用

在子类方法中使用super().add()调用父类的方法。

class Box:
def fn(self):
print("很多很好的代码")
def fn2(self):
print("很好的代码")
class Box2(Box):
def fn(self):
super(Box2, self).fn()
print("新写的代码")
b = Box2()
b.fn()

输出结果:

很多很好的代码
新写的代码

2.2 super().init()

通过super().__init__()调用父类的构造函数,以确保父类的构造函数被正确调用和初始化。

class Box:
def __init__(self, width, height):
self.width = width
self.height = height
class Box2(Box):
def __init__(self, width, height, color):
super(Box2, self).__init__(width, height)
self.color = color
b2 = Box2(10, 20, "red")
print(b2.color)
print(b2.width)

输出结果:

red
10

转载地址:http://aoofk.baihongyu.com/

你可能感兴趣的文章
Python Web开发
查看>>
Redis 配置文件杂项。
查看>>
Python web自动化测试 —— 文件上传
查看>>
Python web自动化测试 —— 文件上传!
查看>>
Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
查看>>
python win32api键盘_Python win32api.keybd_event模拟键盘输入
查看>>
python Windows显示当前鼠标坐标
查看>>
python Workbook 表格宽度
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | grab,一个强大的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>
python | huey,一个非常厉害的 任务调度 Python 库!
查看>>
python | hypothesis,一个有趣的 Python 库!
查看>>
python | Indico,一个超酷的 Python 库!
查看>>
python | isort,一个有趣的 自动整理导入语句 的Python 库!
查看>>
python | jinja,一个超酷的 Python 库!
查看>>
python | joblib,一个强大的 Python 库!
查看>>