1

This is an example from the book "Python In a Nutshell, 3rd ed."

class Const(object):
    def __init__(self, value):
        self.value = value
    def __set__(self, *_):
        pass
    def __get__(self, *_):
        return self.value

class X(object):
    c = Const(23)

x=X()
type(x.c)
>>>> <class 'int'>

c = Const(32)
type(c)
>>>>  <class '__main__.Const'>

Why is the data type of the x.c Integer?

Also, why doesn't the set override descriptor work for c?,

c.value
>>>> 32

c.value = 1
c.value
>>>> 1

It works on the x.c instance

x.c = 1
x.c
>>>> 23
Kimberly
  • 31
  • 3
  • `type(x.c)` is `int` because `Const.__get__` returns `int`. If it were to return an `str` then `type(x.c)` would have been `str` – DeepSpace Jan 15 '20 at 15:35
  • Is there something special under the hood that calls Const. __get__ when a class instance is an attribute of another class? This doesn't happen when the Const instance is not an attribute of another class. – Kimberly Jan 15 '20 at 15:38
  • 1
    I assume ```c.val``` means ```c.value```. In this case you are changing the internal state directly so your defined ```__get/set__``` are not called. – Joshua Nixon Jan 15 '20 at 15:39
  • 2
    Does this answer your question? [Understanding \_\_get\_\_ and \_\_set\_\_ and Python descriptors](https://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors) – CoderCharmander Jan 15 '20 at 15:40
  • 1
    @Kimberly Yes, the rules for how attribute access work change when `__get__` and `__set__` are defined. – chepner Jan 15 '20 at 15:40
  • @CoderCharmander - Thank you for finding that. I read through it all. So, when the attribute is set indirectly (ala as an an instance attribute of another class) then the getters/setter overrides are used. So in order to make a read only class attribute, the class itself has to be an encapsulated in another class. This is odd to me. I wonder why Python chose to do this instead of having the presence of __set__ be enough to override any attempted state change. – Kimberly Jan 15 '20 at 16:06
  • One more thing.. https://pabloariasal.github.io/2018/11/25/python-descriptors/ This is pretty awesome and shows how the @property method can be used to make read only attributes as well – Kimberly Jan 15 '20 at 16:19

0 Answers0