1 '''
2 python与java一样都是面向对象编程(Object-Oriented Programming,OOP),因此也具有封装、继承和多态这三个主要特征
3 通过封装、继承和多态这三个特征,面向对象编程在Python中能够提供模块化、可重用和可扩展的代码结构,使得程序更容易理解和维护。
4 '''
5
6 '''
7 1. 封装(Encapsulation):
8 1. 封装是将数据和方法封装在一个类中,并通过访问修饰符控制对类的属性和方法的访问权限。
9 2. 在Python中,默认情况下,所有的属性和方法都是公开的(public),可以被其他对象直接访问。
10 3. 通过使用双下划线作为前缀,可以定义私有属性或方法,使其只能在类内部被访问。
11 '''
12
13
14 class MyClass:
15 def __init__(self):
16 self.public_var = "This is a public variable"
17 self.__private_var = "This is a private variable"
18
19 def public_method(self):
20 print("This is a public method")
21
22 def __private_method(self):
23 print("This is a private method")
24
25
26 '''
27 2. 继承(Inheritance):
28 1. 继承是指一个类派生出另一个类,并且子类继承了父类的属性和方法。
29 2. 子类可以通过继承获得父类的所有公开成员,并可以在此基础上添加新的属性和方法。
30 3. Python支持单继承和多继承,允许一个子类同时继承自多个父类。
31 '''
32
33
34 class ParentClass:
35 def parent_method(self):
36 print("This is a parent method")
37
38
39 class ChildClass(ParentClass):
40 def child_method(self):
41 print("This is a child method")
42
43
44 obj = ChildClass()
45 obj.parent_method() # 调用父类方法 This is a parent method
46 obj.child_method() # 调用子类方法 This is a child method
47
48 '''
49 3. 多态(Polymorphism):
50 1. 多态是指同一个方法在不同的对象上表现出不同的行为。
51 2. 在Python中,在继承的继承上,多态通过方法重写实现。子类可以重写从父类继承的方法,并以自己特有的方式实现该方法。
52 3. 当调用该方法时,根据对象的实际类型,会执行相应的方法实现。
53 '''
54
55
56 class Shape:
57 def draw(self):
58 pass
59
60
61 class Circle(Shape):
62 def draw(self):
63 print("Drawing a circle")
64
65
66 class Rectangle(Shape):
67 def draw(self):
68 print("Drawing a rectangle") # Drawing a circle、Drawing a rectangle
69
70
71 shapes = [Circle(), Rectangle()]
72
73 for shape in shapes:
74 shape.draw() # 根据对象类型调用相应的draw方法