Python descriptors sharing values ​​between classes

The python descriptor I'm working with shares its value across all instances of its owner class. How can I make the handle of each instance contain its own internal values?

class Desc(object):
    def __init__(self, initval=None,name='val'):
        self.val = initval
        self.name = name

    def __get__(self,obj,objtype):
        return self.val

    def __set__(self,obj,val):
        self.val = val

    def __delete__(self,obj):
        pass


class MyClass(object):
    desc = Desc(10,'varx')

if __name__ == "__main__":
    c = MyClass()
    c.desc = 'max'
    d = MyClass()
    d.desc = 'sally'

    print(c.desc)
    print(d.desc)

The result is this, the last call sets the value for both objects:

localhost $ python descriptor_testing.py 
sally
sally
+3
source share
1 answer

, , self . , (, ), , (, ).

:

class Desc(object):
    default_value = 10
    def __init__(self, name):
        self.name = name

    def __get__(self,obj,objtype):
        return obj.__dict__.get(self.name, self.default_value)
        # alternatively the following; but won't work with shadowing:
        #return getattr(obj, self.name, self.default_value)

    def __set__(self,obj,val):
        obj.__dict__[self.name] = val
        # alternatively the following; but won't work with shadowing:
        #setattr(obj, self.name, val)

    def __delete__(self,obj):
        pass


class MyClass(object):
    desc = Desc('varx')

obj 'varx' __dict__. - , , "" :

class MyClass(object):
    varx = Desc('varx')

, :

MyClass().varx

, :

MyClass().__dict__['varx']

. , "" , .

+7

Source: https://habr.com/ru/post/1725862/


All Articles