DAY 29 复习日:类的装饰器

发布于:2025-06-13 ⋅ 阅读:(20) ⋅ 点赞:(0)

DAY 29 复习日:类的装饰器

1.类的装饰器
def class_decorator(cls):
    def wrapper(*args, **kwargs):
        instance = cls(*args, **kwargs)
        instance.decorated_attribute = 'This attribute was added by the decorator.'
        return instance
    return wrapper

@class_decorator
class MyClass:
    def __init__(self, name):
        self.name = name

my_instance = MyClass('TestName')
print(f'Original name: {my_instance.name}')
print(f'Decorated attribute: {my_instance.decorated_attribute}')

Original name: TestName
Decorated attribute: This attribute was added by the decorator.
2.装饰器思想的进一步理解:外部修改、动态
def dynamic_decorator(func):
    def wrapper(*args, **kwargs):
        print('Before calling the function (added dynamically)')
        result = func(*args, **kwargs)
        print('After calling the function (added dynamically)')
        return result
    return wrapper

def greet():
    print('Hello from the original function!')

greet = dynamic_decorator(greet)
greet()

Before calling the function (added dynamically)
Hello from the original function!
After calling the function (added dynamically)
3.类方法的定义:内部定义和外部定义
class MyClassWithMethods:
    def __init__(self, value):
        self.value = value

    def internal_method(self):
        return f"Internal method called with value: {self.value}"

def external_method_definition(self):
    return f"External method called with value: {self.value}"

MyClassWithMethods.external_method = external_method_definition
my_methods_instance = MyClassWithMethods(100)
print(my_methods_instance.internal_method())
print(my_methods_instance.external_method())

Internal method called with value: 100
External method called with value: 100
作业:复习类和函数的知识点,写下自己过去29天的学习心得,如对函数和类的理解,对python这门工具的理解等,未来再过几个专题部分我们即将开启深度学习部分。

函数就像是程序中的一个个独立且可重复使用的“积木”。它们封装了特定的操作或计算逻辑,让你能将复杂的任务分解成更小、更易于管理的部分。这种设计不仅大大提升了代码的复用性,避免了重复编写相同代码的麻烦,也使得你的程序结构更清晰、更有条理,就像搭建乐高模型一样,每一块积木都有它的位置和功能。通过函数,你只需关注它能做什么,而不必深入了解它内部的实现细节,这极大简化了编程的认知负担。

类就是对现实世界中事物的“蓝图”。它们将相关的数据(属性)和操作这些数据的方法(行为)紧密结合在一起,形成一个有机的整体。你可以把类看作是制造某种具体“东西”的模具,比如“汽车”这个类,它定义了所有汽车共有的特征(颜色、品牌)和能力(启动、加速)。通过这个蓝图,你可以创建出无数个独特的“对象”或“实例”,每个对象都拥有蓝图所定义的属性和行为,但具体的值可能不同。类是面向对象编程的核心,它让代码更贴近人类的思维方式,也为代码的继承和多态提供了基础,使得程序设计更灵活、更易于扩展。

Python以简洁的语法和极高的可读性著称,让你能用更少的代码完成更多的事情。Python“开箱即用”的哲学,配合其庞大且活跃的生态系统和第三方库,使得它几乎无所不能——无论是数据分析、Web开发、人工智能,还是自动化脚本,Python都能游刃有余。它降低了编程的门槛,让开发者能将更多精力放在解决问题本身,而非语言的复杂性上。总的来说,Python是一门强大、灵活且极具生产力的工具,无论你是编程新手还是资深开发者,它都能成为你高效完成任务的得力助手。

@浙大疏锦行


网站公告

今日签到

点亮在社区的每一天
去签到