描述器

描述器#

class Ten:
    def __get__(self, obj, objtype=None):
        return 10
class Ten:
    def __get__(self, obj, objtype=None):
        x = 1
        print("局部变量1:", locals()["x"])
        print("参数:\n", obj, objtype)
        x = 12
        print("局部变量2:", locals()["x"])
        print("x:", x)
        return 10
import logging

logging.basicConfig(level=logging.INFO)

class LoggedAgeAccess:
    def __get__(self, obj, objtype=None):
        value = obj._age
        logging.info('Accessing %r giving %r', 'age', value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', 'age', value)
        obj._age = value

class Person:
    age = LoggedAgeAccess()
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def birthday(self):
        self.age += 1  
mary = Person('Mary M', 30)
mary.age = 20
add.cache
{'add': [3, 3]}
add(1, 4)
0:  {'x': 1, 'y': 4, 'result': 5}
5
add.cache
{'add': [3, 3, 5, 5]}
@Function
def add2(x, y):
    result = x + y * 2
    return result
Function.cache
{'add': [3, 3, 5, 5], 'add2': []}
add2(3, 4)
11
Function.cache
{'add': [3, 3, 5, 5], 'add2': [11]}