Python快速而美丽[v1.0.0][面向对象]

本文深入探讨Python面向对象编程的核心概念,包括类、对象、继承、封装、多态及特殊方法,通过实例讲解如何利用OOP提升代码质量和可维护性。

Python 是一种支持多种编程范式的语言,其中面向对象编程 (OOP) 是其核心特性之一。面向对象编程是一种编程范式,它使用“对象”——即数据和操作数据的方法的封装体——来设计软件。在 Python 中,几乎一切都是一个对象,这使得 OOP 在 Python 中非常直观且强大。

以下是 Python 面向对象编程的一些关键概念和语法:

类 (Class)

类是用于创建对象的蓝图。它们定义了一组属性和方法,这些属性和方法被所有该类的实例共享。

class MyClass:
    # 类变量
    class_variable = "I am shared by all instances"

    def __init__(self, instance_variable):
        # 实例变量
        self.instance_variable = instance_variable

    def method(self):
        print("This is a method of MyClass")

对象 (Object)

对象是类的实例。你可以通过调用类来创建对象,并通过点运算符访问对象的属性和方法。

my_object = MyClass("I am unique to this instance")
print(my_object.instance_variable)  # 输出: I am unique to this instance
my_object.method()                  # 输出: This is a method of MyClass

继承 (Inheritance)

继承允许一个类继承另一个类的属性和方法。这有助于代码的复用和模块化。

class ChildClass(MyClass):
    def child_method(self):
        print("This is a method of ChildClass")

child_object = ChildClass("Child instance variable")
child_object.method()              # 输出: This is a method of MyClass
child_object.child_method()        # 输出: This is a method of ChildClass

封装 (Encapsulation)

封装是隐藏对象的内部状态和实现细节的过程。Python 使用下划线 _ 和双下划线 __ 来实现封装。

  • 单下划线 _ 通常表示属性或方法是内部使用的,但并不阻止外部访问。
  • 双下划线 __ 创建了一个名称重整(name mangling)的私有属性或方法,虽然仍然可以从外部访问,但需要使用 _classname__private_name 这样的特殊语法。

多态 (Polymorphism)

多态是指子类能够重写父类的方法,从而让不同的对象以相同的方式被调用,但实际上执行的是特定于类的行为。

class AnotherChildClass(MyClass):
    def method(self):
        print("This is a redefined method in AnotherChildClass")

another_child = AnotherChildClass("Another child instance variable")
another_child.method()             # 输出: This is a redefined method in AnotherChildClass

特殊方法 (Special Methods)

Python 提供了一系列特殊的魔术方法(或称为特殊方法),如 __init__, __str__, __repr__ 等,这些方法提供了对象的初始化、字符串表示、调试信息等功能。

class MyStrClass:
    def __init__(self, string):
        self.string = string

    def __str__(self):
        return f"My string is: {self.string}"

    def __repr__(self):
        return f"MyStrClass('{self.string}')"

my_str = MyStrClass("Hello, world!")
print(str(my_str))      # 输出: My string is: Hello, world!
print(repr(my_str))     # 输出: MyStrClass('Hello, world!')

以上就是 Python 面向对象编程的基本概念和语法。理解并熟练掌握这些概念对于开发高质量的 Python 应用程序至关重要。

代码示例

# encoding = utf-8

"""
面向对象第一大特征:封装
基于Python3
"""


class CellPhone:
    """
    手机类
    """
    def __init__(self, cell_phone_number):
        self.cell_phone_number = cell_phone_number
        self.battery_percentage = 100

    def dial(self, cell_phone_number):
        print("Calling %s" % cell_phone_number)

    def send_sms(self, cell_phone_number, message):
        print("Sending %s to %s" % (message, cell_phone_number))

    def start_charge(self):
        print("Charging...")

    def stop_charge(self):
        print("Charge Finished")


if __name__ == '__main__':
    P30 = CellPhone("159xxxxxxxx")
    P40 = CellPhone("180xxxxxxxx")
    print("P30 手机号是 %s" % P30.cell_phone_number)
    print("P30 手机还剩余电量 %d" % P30.battery_percentage)

    P40.battery_percentage = 50
    print("P40 手机号是 %s" % P40.cell_phone_number)
    print("P40 手机还剩余电量 %d" % P40.battery_percentage)

    P30.dial(P40.cell_phone_number)
    P40.send_sms(P30.cell_phone_number, "Give u feedback later")
# encoding = utf-8
from OOP import CellPhone


class SymbianMobilePhone(CellPhone):
    """
    塞班手机
    """
    pass


class SmartMobilePhone(CellPhone):
    """
    智能手机
    """
    def __init__(self, cell_phone_number, os="Android"):
        super().__init__(cell_phone_number)
        self.os = os
        self.app_list = list()
    
    def download_app(self, app_name):
        print("正在下载应用 %s" % app_name)
        
    def delete_app(self, app_name):
        print("正在删除应用 %s" % app_name)
        

class FullSmartMobilePhone(SmartMobilePhone):
    """
    全面屏智能手机
    """
    def __init__(self, cell_phone_number, screen_size, os="Android"):
        super().__init__(cell_phone_number, os)
        self.screen_size = screen_size


class FolderScreenSmartMobilePhone(SmartMobilePhone):
    """
    折叠屏智能手机
    """
    def fold(self):
        print("The CellPhone is folded")
        
    def unfold(self):
        print("The CellPhone is unfolded")

# encoding = utf-8
class IPhone:
    """
    IPhone基类,具有一个解锁功能
    """
    def unlock(self, pass_code, **kwargs):
        print("解锁IPhone")
        return True


class IPhone5S(IPhone):
    """
    IPhone5S,unlock功能增加了指纹解锁
    """
    def finger_unlock(self, fingerprint):
        return True

    def unlock(self, pass_code, **kwargs):
        fingerprint = kwargs.get("fingerprint", None)
        if self.finger_unlock(fingerprint):
            print("指纹解锁成功")
            return True
        else:
            return super().unlock(pass_code)


class IPhoneX(IPhone):
    """
    IPhoneX, unlock功能增加刷脸解锁
    """
    def face_unlock(self, face_id):
        return True

    def unlock(self, pass_code, **kwargs):
        face_id = kwargs.get("face_id", None)
        if self.face_unlock(face_id):
            print("通过刷脸解锁成功")
            return True
        else:
            super().unlock(pass_code)
from abc import ABCMeta, abstractmethod

class MobilePhone(metaclass=ABCMeta):

    @abstractmethod
    def unlock(self, credential):
        pass

class IPhone(MobilePhone):
    def unlock(self, credential):
        print("IPhone解锁")

class IPhone5S(MobilePhone):
    def unlock(self, credential):
        print("5S解锁")

class IPhoneX(MobilePhone):
    def unlock(self, credential):
        print("IPhoneX解锁")

def test_unlock(phone):
    if isinstance(phone, IPhone):
        phone.unlock("......")
    else:
        print("传入的参数必须是MobilePhone类型")
        return False


if __name__ == '__main__':
    phone = IPhone()
    test_unlock(phone)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Davieyang.D.Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值