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 instancemy_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 MyClasschild_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-8class 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-8from OOP import CellPhoneclass SymbianMobilePhone(CellPhone): """ 塞班手机 """ passclass 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_sizeclass FolderScreenSmartMobilePhone(SmartMobilePhone): """ 折叠屏智能手机 """ def fold(self): print("The CellPhone is folded") def unfold(self): print("The CellPhone is unfolded")
# encoding = utf-8class IPhone: """ IPhone基类,具有一个解锁功能 """ def unlock(self, pass_code, **kwargs): print("解锁IPhone") return Trueclass 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, abstractmethodclass MobilePhone(metaclass=ABCMeta): @abstractmethod def unlock(self, credential): passclass 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 Falseif __name__ == '__main__': phone = IPhone() test_unlock(phone)