1

I want to create a proxy in Python because of function and attributes access (something like private). I create the proxy with references to functions in the source object. But I have a problem, that functions have no problem with changing attributes but property yes. Here is an example:

A working example

class A:
    def __init__(self):
        self.value = 1

    def get_value(self):
        return self.value

class Proxy:
    def __init__(self, cls):
        self.get_value = cls.get_value
        # del cls

a = A()
p = Proxy(a)

print(a.get_value(), p.get_value())
a.value = 2
print(a.get_value(), p.get_value())

Output:

1 1
2 2

Not working:

class A:
    def __init__(self):
        self.value = 1

    @property
    def get_value(self):
        return self.value

class Proxy:
    def __init__(self, cls):
        self.get_value = cls.get_value
        # del cls

a = A()
p = Proxy(a)

print(a.get_value, p.get_value)
a.value = 2
print(a.get_value, p.get_value)

Output:

1 1
2 1

Can someone explain me where the problem is and if there is any solution for this? I could use functions, but I think @property is more Python solution. And I really want to know what is the difference. Thank you

  • Answers [here](https://stackoverflow.com/questions/3681272/can-i-get-a-reference-to-a-python-property) might help you understand and solve your problem – yorodm Feb 27 '19 at 22:50

1 Answers1

0

In Proxy.__init__, you end up executing:

self.get_value = a.get_value

and very different things happen in your two examples.

In the first case, a.get_value is a method of a. So, calling p.get_value() is the same as calling a.get_value(). You get identical results.

In the second case, you have already defined a.get_value as a property, so self.get_value = a.get_value is basically self.get_value = 2, it is just an int attribute of p.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50