探讨Python中面向对象编程(OOP)的应用实例
Python是一种支持面向对象编程的高级语言。以下是一些Python中OOP的应用实例:
创建学生对象
student = Student(“Tom”, 9)
2. **继承**:
```python
# 子类继承父类
class YoungStudent(Student):
def special_activity(self):
return f"{self.name} is participating in a special activity"
# 创建子类对象
young_student = YoungStudent("Alice", 10, special_activity=lambda: "Unique activity"))
print(young_student.special_activity()) # Output: Alice is participating in a special activity
封装:
```python属性私有化
class Person:
def init(self, name, age):self.name = name
self.__age = age # 私有属性
@property # 访问器方法,对外提供读取的途径
def age(self):return self.__age
创建对象并访问私有属性
person = Person(“John”, 30)
print(person.age) # 输出: 30
```
以上就是Python中面向对象编程的一些应用实例。
还没有评论,来说两句吧...