Not sure if this is feasible or not. The implementation/example below is dummy, FYI.
I have a Python class, Person. Each person has a public first name and a public last name attribute with corresponding private attributes - I'm using a descriptor pattern to manage access to the underlying private attributes.
I am using the descriptor to count the number of times the attribute is accessed as well as obtain the underlying result.
class AttributeAccessCounter:
def __init__(self):
self._access_count = 0
def __get__(self, instance, owner):
self._access_count += 1
return getattr(instance, self.attrib_name)
def __set_name__(self, obj, name):
self.attrib_name = f'_{name}'
@property
def counter(self):
return self._access_count
class Person:
first = AttributeAccessCounter()
last = AttributeAccessCounter()
def __init__(self, first, last):
self._first = first
self._last = last
From an instance of the class Person, how can I access the _access_count or property counter?
john = Person('John','Smith')
print(john.first) # 'John'
print(john.first.counter) # AttributeError: 'str' object has no attribute 'counter'
if instance is None: return self._access_countas the first line of__get__(), you could retrieve the count viaPerson.first._access_counton the descriptor itself. That means the count is global, not per-instance - it tracks the number of times the attribute has been accessed across all instances ofPerson. Is this what you really wanted?