P
P
pythonMyLife2021-03-05 21:45:51
Python
pythonMyLife, 2021-03-05 21:45:51

Why doesn't the handle work as it should?

I'm writing a permanent property handle, but when I use it it doesn't work at all like it's supposed to!

The code:

class Permanent_property ():
    def __init__(self, raise_exception: bool = True):
        print(f'Init {self} with {raise_exception = }')
        self.___exception = raise_exception 
        self.___instance  = None

    def __get__(self, obj, cls):
        print(f'Get {self} for {obj} of {cls}')
        return self.___instance

    def __set__(self, obj, val):
        print('Set {self} for {obj} {val = }')
        if self.___instance is None:
            self.___instance = val

        else:
            if self.___exception:
                raise AttributeError('Permanent property for {obj} is alreadly setted')


Usage:

>>> class A ():
... def __init__ (self):
...     self.attr = Permanent_property ()	
>>> a = A()
Init <__main__.Permanent_property object at 0x0000023905744910> with raise_exception = True
>>> a.attr
<__main__.Permanent_property object at 0x0000023905744910>


And for some reason python doesn't consider it as a property descriptor, but as a normal property. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2021-03-05
@pythonMyLife

You open the dock.
Reading:

Descriptors only work when used as class variables. When put in instances, they have no effect.

Correcting your code:
class A:
 attr = Permanent_property()	

 def __init__(self, something):
    self.attr = something

Keep reading:
https://docs.python.org/3/howto/descriptor.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question