How to implement this mechanism:

I want to implement a dynamic relationship mechanism with python something like this:

a:=10
b:=30
c:=a+b
print c
a+=20
print c

output:

40
60

c is always the result of a + b.
therefore, if a or b change, then c automatically updates the value. I write code in C # and do it using the setand mechanism get. Now you need to translate it into python code for use in another program (FontLab Studio 5). I am not very familiar with Python. does it have a function get,setlike C #? if not ho implement one?

+3
source share
4 answers

New Python classes support properties .

+2
source

, , , , / Python :

class Calc(object):
    def __init__(self, a = 0, b = 0):
        self._a = a
        self._b = b

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, value):
        self._b = value

    @property
    def c(self):
        return self._a + self._b

    def __str__(self):
        return str(self.c)

calc = Calc()
calc.a = 1
calc.b = 2
print calc.c
calc.a += 10
print calc.c

a b, :

class Calc(object):
    def __init__(self, a = 0, b = 0):
        self.a = a
        self.b = b

    @property
    def c(self):
        return self.a + self.b

    def __str__(self):
        return str(self.c)
+4

In your situation, c is actually a function that needs to be called. You can use something like this:

a = 10
b = 30
c = lambda: a + b

print c()
a += 20
print c()

If you don't like the method call being made explicit to c, you can use a generic Calc object that hides this implementation:

class Calc(object):
    def __init__(self):
        object.__setattr__(self,  '_params', dict())

    def __getattr__(self, name):
        param = self._params[name]
        if callable(param):
            return param()
        else:
            return param

    def __setattr__(self, name, value):
        self._params[name] = value

    def __delattr__(self, name):
        del self._params[name]

And then you could do:

c = Calc()
c.a = 10
c.b = 30
c.c = lambda: c.a + c.b

print c.c
c.a += 20
print c.c
+3
source

something like that:

class C:
  def __init__(self):
    self.x = 0
    self.y = 0

  def get(self):
    return self.x + self.y

  def __str__(self):
    return self.__unicode__()

  def __unicode__(self):
    return str(self.get())

c = C()
c.x = 1
print c
c.y =2
print c

With new style classes and annotations, you can probably do it better.

+1
source

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


All Articles