一个网站要怎么做的吗,国内it培训机构排名,梅州建设工程交易中心网站,在线高清观看免费ppt1、面向对象编程概述
面向对象编程#xff08;OOP#xff09;是一种编程范式#xff0c;它以“对象”为核心#xff0c;将数据和操作封装在对象中#xff0c;通过类和对象来实现代码的组织和复用。在Python3中#xff0c;面向对象编程是其重要的特性之一。
2、类与对象…1、面向对象编程概述
面向对象编程OOP是一种编程范式它以“对象”为核心将数据和操作封装在对象中通过类和对象来实现代码的组织和复用。在Python3中面向对象编程是其重要的特性之一。
2、类与对象
1.类Class类是对象的蓝图或模板它定义了具有相同属性和方法的对象的集合。类定义了该集合中每个对象所共有的属性和方法。
class MyClass: def __init__(self, value): self.value value def my_method(self): print(fThe value is {self.value})
2.对象Object对象是类的实例它包含了类定义的属性和方法。
obj MyClass(10)
print(obj.value) # 输出: 10
obj.my_method() # 输出: The value is 10
3、实例方法
实例方法是定义在类中并且需要通过对象来调用的方法。它们通常操作对象的状态即属性。
class Person: def __init__(self, name): self.name name def greet(self): print(fHello, my name is {self.name}) p Person(Alice)
p.greet() # 输出: Hello, my name is Alice
4、封装
封装是面向对象编程的四大特性之一它主要用来隐藏对象的属性和实现细节仅对外提供公共访问方式。这样可以保证对象内部状态的安全并减少代码的复杂性。
class Encapsulated: def __init__(self, value): self.__value value # 使用双下划线实现私有属性 def get_value(self): return self.__value def set_value(self, new_value): self.__value new_value
5、继承
继承是面向对象编程的另一个重要特性它允许一个类派生类或子类继承另一个类基类或父类的属性和方法。
1.单继承子类只继承自一个父类。
class Parent: def say_hello(self): print(Hello from Parent) class Child(Parent): pass c Child()
c.say_hello() # 输出: Hello from Parent
2.多继承子类可以继承自多个父类。
class Parent1: def say_hello1(self): print(Hello from Parent1) class Parent2: def say_hello2(self): print(Hello from Parent2) class Child(Parent1, Parent2): pass c Child()
c.say_hello1() # 输出: Hello from Parent1
c.say_hello2() # 输出: Hello from Parent2
6、多态
多态意味着不同的对象对同一消息作出响应。在Python中多态是通过方法重写和继承实现的。
class Shape: def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius radius def area(self): return 3.14 * self.radius ** 2 class Rectangle(Shape): def __init__(self, width, height): self.width width self.height height def area(self): return self.width * self.height def calculate_area(shape): return shape.area() circle Circle(5)
rectangle Rectangle(4, 6) print(calculate_area(circle)) # 调用Circle的area方法
print(calculate_area(rectangle)) # 调用Rectangle的area方法
7、私有属性与方法
在Python中通常使用双下划线前缀来实现私有属性和方法。这样这些属性和方法就不能直接从类的外部访问但可以通过类内部提供的公共方法进行访问和操作。
class MyClass: def __init__(self, value): self.__private_value value # 私有属性 def __private_method(self): # 私有方法 print(This is a private method) def get_private_value(