python装饰器,闭包,Python动态语言-动态添加属性和方法

文章探讨了Python编程中的闭包函数,展示了如何使用闭包来封装和重用代码。接着,解释了装饰器的工作原理,通过示例说明了如何使用装饰器来增强函数的功能。此外,还介绍了如何动态地给Python类和对象添加方法和属性,包括实例方法、类方法和静态方法的使用。最后,提供了一些具体的代码示例来展示这些概念。
摘要由CSDN通过智能技术生成
#闭包函数,其中 exponent 称为自由变量
# def nth_power(exponent):
#     def exponent_of(base):
#         return base ** exponent
#     return exponent_of # 返回值是 exponent_of 函数
# square = nth_power(2) # 计算一个数的平方
# cube = nth_power(3) # 计算一个数的立方
#
# print(square((square(2))))  # 计算 2 的平方
# print(cube(cube(2))) # 计算 2 的立方



# def nth_power(exponent):
#     def exponent_of(base):
#         return base ** exponent
#     return exponent_of
# square = nth_power(2)
# #查看 __closure__ 的值
# print(square.__closure__)


# 装饰器
#funA 作为装饰器函数
# def funA(fn):
#     print("C语言中文网")
#     fn() # 执行传入的fn参数
#     print("http://c.biancheng.net")
#     return "装饰器函数的返回值"
#
# @funA
# def funB():
#     print("学习 Python")

#
# 通过比对以上 2 段程序不难发现,使用函数装饰器 A() 去装饰另一个函数 B(),其底层执行了如下 2 步操作:
# 将 B 作为参数传给 A() 函数;
# 将 A() 函数执行完成的返回值反馈回  B。




# def funA(fn):
#     # 定义一个嵌套函数
#     def say(arc):
#         print("Python教程:",arc)
#     return say
#
# @funA
# def funB(arc):
#     print("funB():", a)
# funB("http://c.biancheng.net/python")

def funA(fn):
    # 定义一个嵌套函数
    def say(*args,**kwargs):
        fn(*args,**kwargs)
    return say

@funA
def funB(arc):
    print("C语言中文网:",arc)

@funA
def other_funB(name,arc):
    print(name,arc)
funB("http://c.biancheng.net")
other_funB("Python教程:","http://c.biancheng.net/python")


Python @函数装饰器及用法(超级详细)

Python动态语言-动态添加属性和方法

import types

#定义了一个类
class Person(object):
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")

#定义一个实例方法
def run(self, speed):
    print("%s在移动, 速度是 %d km/h"%(self.name, speed))

#定义一个类方法
@classmethod
def testClass(self):
    self.num = 100
    print('nyou nn n nn 1')
#定义一个静态方法
@staticmethod
def testStatic():
    print("---static method----")

#动态给对象添加方法
a=Person('网格',20)
a.run=types.MethodType(run,a)
a.run(180)
#动态给类添加方法(类方法和静态方法)静态方法
b=Person('静哥',25)
Person.meth=testStatic
b.meth()
#类方法
c=Person('进哥',22)
Person.test=testClass
print(c.test())

给Python的类和对象动态增加属性和方法 - phyger - 博客园
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值