1

I've this descriptor:

# Generic descriptor
class Attribute(object):
    def __init__(self, value):
        self.value = value
    def __get__(self, instance, value):
        return self.value
    def __set__(self, instance, value):
        self.value = value

I would add an attribute 'modified' to check if an instance of descriptor is modified. Es.

# Generic descriptor
class Attribute(object):
    def __init__(self, value):
        self.value = value
        self.modified = False
    def __get__(self, instance, value):
        return self.value
    def __set__(self, instance, value):
        self.value = value
        self.modified = True

How I can do this ?

1 Answer 1

2

Note that in your __get__ and __set__ methods, you actually want to access instance, not self (self being the actual Attribute object).

Here is one way of doing it:

class Attribute(object):
    def __init__(self, attr):
        self.attr = attr
    def __get__(self, instance, owner):
        return getattr(instance, self.attr)
    def __set__(self, instance, value):
        setattr(instance, self.attr, value)
        instance.modified = True

class A(object):
    def __init__(self):
        self._f = 0
        self.modified = False
    f = Attribute('_f')

a = A()
a.f
=> 0
a.modified
=> False
a.f = 33
a.modified
=> True

Of course, this snippet can be improved in many ways, depending on what you're trying to achieve.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.