0

If I have a class such as this

class foo():
    def __init__(self, value = 0):
        self.__value = value
    def __set__(self, instance, value):
        self.__value = value
    def calc(self):
        return self.__value * 3
    def __repr__(self):
        return str(self.__value)

I can now make a variable of the class foo and use it's functions.

n = foo(3)
print(n.calc())

No problems there but if I keep going with something like this.

n = 5
print(n.calc())

I will get an error, because I have now set n to an int object with the value 5 and thus does not have the calc() function.

I normally work with C++ so I'm confused because I thought that the __set__ function was supposed to override the = operator and then set __value to the value of 5 just like if I were to to use

operator=(int value)

In C++, I have looked for an explanation but have not found any.

All help appreciated.

  • Briefly: you can't do that, as you saw. Continue to use the strategy that actually works. – TigerhawkT3 Mar 24 '17 at 10:17
  • 1
    @TigerhawkT3 I don't think the question is about extending int, rather about why the `__set__` doesn't work as expected. – PidgeyUsedGust Mar 24 '17 at 10:21
  • 1
    @TigerhawkT3 just as Pidgey suggested I was asking why \__set__ does not work as I thought it would initially. Secondly I think it's kind of unfair for you to mark my question as a duplicate since both of your examples are drastically different in how they were worded compared to mine. How am supposed to find those questions when I word them so differently, I know the "Mark as duplicate" button can be very tempting when that power has been bestowed upon you but please consider it more carefully. – John McBluffin Mar 25 '17 at 17:21
  • No one is saying you were supposed to have found those other questions. Closure isn't a punishment. – TigerhawkT3 Mar 25 '17 at 22:46
  • @TigerhawkT3 Fair point. – John McBluffin Mar 26 '17 at 01:12

1 Answers1

0

As stated here.

The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).

PidgeyUsedGust
  • 797
  • 4
  • 11