samedi 10 février 2018

Descriptor pattern : trouble with property and instance attribute

I have implemented the following descriptor class. I want to follow Player instances attribute credit.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-


class SignalDescriptor(object):

    subscriptions = {}

    @classmethod
    def warn_me(cls, obj, attr, callback):
        cls.subscriptions.setdefault(obj, {}).setdefault(attr,
                                                         set()).add(callback)

    def __init__(self, name, value_init=None):
        self.name = name
        self.value = value_init

    def __get__(self, obj, objtype):
        for callback in self.subscriptions.get(obj, {}).get(self.name, ()):
            callback('get', obj, self.name, self.value)
        return self.value

    def __set__(self, obj, value):
        for callback in self.subscriptions.get(obj, {}).get(self.name, ()):
            callback('set', obj, self.name, self.value, value)
        self.value = value


class Player(object):

    credits = SignalDescriptor("credits", 0)


def monitor_credits(action, obj, attribut, current_value, new_value=None):

    if action == 'set':
        print("Credits have been changed:")
    else:
        print("Credits have been consulted:")
    print(action, obj, attribut, current_value, new_value)

MY PROBLEM IS :

1-how to follow multiple instances (ie j1.credits, j2.credits,j3.credits) I dont know how to re-write my pattern to survey instance attributes, i have here only class attribute survey.

2-How to survey property with my pattern:

Lets look another example: I dont care about Width or Height change, only surface matters : how to syntax my descriptor pattern ,or my Shape class to accept it,in thise case ?

class Shape():
    def __init__(self, Width=1, Height=1):
        self.Width = Width
        self.Height = Height

    @property
    def surface(self):
        return self.Width * self.Height

rect1 = Shape(3, 4)
rect2 = Shape(4, 3)

Aucun commentaire:

Enregistrer un commentaire