python3 面向对象示例代码
所属分类 python
浏览量 5
Python 面向对象编程
类和实例:创建 Animal 基类和 Dog、Cat 子类
继承:Dog 和 Cat 继承自 Animal 类
多态:通过 animal_sound 函数演示方法重写
封装:使用单下划线和双下划线实现属性访问控制
抽象基类:定义 Shape 抽象类和 Rectangle 实现
类属性和类方法:Counter 类记录实例数量
静态方法:MathUtils 类提供通用工具方法
SyntaxError: Non-ASCII character '\xe5' in file oop_example.py on line 1, but no encoding declared
Python 默认使用 ASCII 编码读取文件,当文件中包含非 ASCII 字符(如中文)时,需要在文件开头声明编码格式
# -*- coding: utf-8 -*-
python oop_example.py
python2 版本运行报错 ,python3 ok
python -v
# -*- coding: utf-8 -*-
# oop_example.py
# 基类:动物
class Animal:
def __init__(self, name, age):
self.name = name # 公有属性
self._age = age # 受保护属性(单下划线)
self.__species = "Unknown" # 私有属性(双下划线)
def speak(self):
"""基类方法,子类可重写"""
return "动物发出声音"
def get_age(self):
"""获取私有属性 age 的方法"""
return self._age
def set_age(self, age):
"""设置私有属性 age 的方法"""
if age > 0:
self._age = age
def info(self):
"""返回动物信息"""
return f"{self.name} 年龄: {self._age}"
# 子类:狗(继承自 Animal)
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed # 子类新增属性
def speak(self):
"""重写基类方法"""
return f"{self.name}({self.breed})汪汪叫"
def fetch(self):
"""子类特有方法"""
return f"{self.name} 在玩接球游戏"
# 子类:猫(继承自 Animal)
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color # 子类新增属性
def speak(self):
"""重写基类方法"""
return f"{self.name}({self.color})喵喵叫"
def climb(self):
"""子类特有方法"""
return f"{self.name} 在爬树"
# 多态示例函数
def animal_sound(animal):
"""接收任意 Animal 子类对象,调用其 speak 方法"""
print(animal.speak())
# 抽象基类(使用 abc 模块)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
"""抽象方法,子类必须实现"""
pass
def describe(self):
"""普通方法"""
return "这是一个形状"
# 实现抽象类
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
"""实现抽象方法"""
return self.width * self.height
# 类属性和类方法
class Counter:
instances = 0 # 类属性,记录创建的实例数量
def __init__(self):
Counter.instances += 1 # 每次创建实例时增加计数
@classmethod
def get_instance_count(cls):
"""类方法,访问类属性"""
return cls.instances
# 静态方法示例
class MathUtils:
@staticmethod
def add(a, b):
"""静态方法,不依赖类或实例"""
return a + b
# 使用示例
if __name__ == "__main__":
# 创建实例
dog = Dog("Buddy", 3, "金毛")
cat = Cat("Whiskers", 2, "白色")
# 访问属性和方法
print(dog.info()) # 输出: Buddy 年龄: 3
print(dog.speak()) # 输出: Buddy(金毛)汪汪叫
print(dog.fetch()) # 输出: Buddy 在玩接球游戏
print(cat.info()) # 输出: Whiskers 年龄: 2
print(cat.speak()) # 输出: Whiskers(白色)喵喵叫
print(cat.climb()) # 输出: Whiskers 在爬树
# 多态
animal_sound(dog) # 输出: Buddy(金毛)汪汪叫
animal_sound(cat) # 输出: Whiskers(白色)喵喵叫
# 抽象类
rect = Rectangle(5, 4)
print(f"矩形面积: {rect.area()}") # 输出: 矩形面积: 20
print(rect.describe()) # 输出: 这是一个形状
# 类属性和类方法
c1 = Counter()
c2 = Counter()
print(f"创建的 Counter 实例数量: {Counter.get_instance_count()}") # 输出: 2
# 静态方法
print(f"1 + 2 = {MathUtils.add(1, 2)}") # 输出: 1 + 2 = 3
# 封装演示
dog.set_age(4) # 通过公有方法修改私有属性
print(f"{dog.name} 新年龄: {dog.get_age()}") # 输出: Buddy 新年龄: 4
# 注意:直接访问私有属性会报错
# print(dog.__species) # 报错:'Dog' object has no attribute '__species'
上一篇
提示词工程要点
AI RAG开发 要点
AI agent开发要点