描述器

描述器#

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)
INFO:root:Updating 'age' to 30
mary.age = 20
INFO:root:Updating 'age' to 20
add.cache
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 add.cache

NameError: name 'add' is not defined
add(1, 4)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 add(1, 4)

NameError: name 'add' is not defined
add.cache
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 1
----> 1 add.cache

NameError: name 'add' is not defined
@Function
def add2(x, y):
    result = x + y * 2
    return result
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 @Function
      2 def add2(x, y):
      3     result = x + y * 2
      4     return result

NameError: name 'Function' is not defined
Function.cache
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 Function.cache

NameError: name 'Function' is not defined
add2(3, 4)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 add2(3, 4)

NameError: name 'add2' is not defined
Function.cache
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 Function.cache

NameError: name 'Function' is not defined