# 定义类和创建对象
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
stu = Student('Alice', 95)
print(stu.name, stu.score)
__init__
,用于初始化对象__del__
,对象销毁时自动调用
class Student:
school = 'YunfanEdu' # 类属性
def __init__(self, name, score):
self.name = name # 实例属性
self._secret = '私有数据' # 约定私有属性
stu = Student('Bob', 88)
print(stu.name, stu.school)
print(stu._secret) # 不建议外部访问
class Demo:
def instance_method(self):
print('实例方法')
@classmethod
def class_method(cls):
print('类方法')
@staticmethod
def static_method():
print('静态方法')
d = Demo()
d.instance_method()
Demo.class_method()
Demo.static_method()
class Person:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError('年龄不能为负')
self._age = value
p = Person(18)
p.age = 20
print(p.age)
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return f"Student({self.name}, {self.score})"
def __eq__(self, other):
return self.name == other.name and self.score == other.score
stu1 = Student('Alice', 95)
stu2 = Student('Alice', 95)
print(stu1)
print(stu1 == stu2)
class Animal:
def speak(self):
print('动物叫')
class Dog(Animal):
def speak(self):
super().speak()
print('汪汪!')
d = Dog()
d.speak()
class Cat:
def speak(self):
print('喵喵!')
def animal_speak(animal):
animal.speak()
for a in [Dog(), Cat()]:
animal_speak(a)
class Engine:
def start(self):
print('发动机启动')
class Car:
def __init__(self):
self.engine = Engine() # 组合
def drive(self):
self.engine.start()
print('汽车行驶')
car = Car()
car.drive()
print(Car.__mro__)
class Student:
def __init__(self, name):
self.name = name
self.scores = {}
def add_score(self, subject, score):
self.scores[subject] = score
def show_all(self):
print(f"{self.name}的成绩:")
for subject, score in self.scores.items():
print(f" {subject}: {score}")
stu = Student('Alice')
stu.add_score('Math', 95)
stu.add_score('English', 88)
stu.show_all()
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print('余额不足')
else:
self.balance -= amount
class AccountFactory:
@staticmethod
def create_account(owner):
return Account(owner)
acc = AccountFactory.create_account('Tom')
acc.deposit(100)
print(acc.balance)
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def is_square(self):
return self.width == self.height
rect = Rectangle(3, 4)
print('面积:', rect.area())
print('周长:', rect.perimeter())
print('是否正方形:', rect.is_square())
# __str__和__repr__调试
class Demo:
def __repr__(self):
return ''
print(Demo())
# isinstance判断
print(isinstance(rect, Rectangle))
实现一个系统,支持录入多个学生的多门课程成绩,统计每个学生的平均分、最高分、最低分,并能按课程统计全班平均分。
实现一个图形管理系统,支持添加多种图形对象,计算总面积、最大面积、最小面积等。
实现单例、工厂、观察者等常见OOP设计模式的Python代码示例。
用UML类图工具画出你的类结构,并分析其高内聚、低耦合特性。