Python Forum
API REST Package for Calling/Flask - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: API REST Package for Calling/Flask (/thread-35285.html)

Pages: 1 2


RE: API REST Package for Calling/Flask - muzikman - Oct-20-2021

I do understand the concept of name mangling and it's not to fool the user of the class because everything is open (pythonic way), it's just an understood rule, don't touch this please.

Last question:

Why use them at all, or when? What questions should I ask myself when designing a class to see if I need them?


RE: API REST Package for Calling/Flask - snippsat - Oct-21-2021

(Oct-20-2021, 07:28 PM)muzikman Wrote: Why use them at all, or when? What questions should I ask myself when designing a class to see if I need them?
Would say in most cases leave it public.
I mean,do not add anything to obscure the name of your attribute if not needed.
Look into properties when need to add more control over the attributes.
Let say want control/protect the input US(120V) and Europe(220V).
class Voltage():
    def __init__(self, voltage=220, current=15):
        self.current = current
        self._voltage = voltage

    @property
    def voltage(self):
        return(self._voltage)

    @voltage.setter
    def voltage(self, voltage):
        if voltage in [120, 220]:
            self._voltage = voltage
        else:
            print("The Voltage value has to be either 120 or 240")
Usage:
>>> set_power = Voltage()
>>> set_power.voltage
220
>>> set_power.current
15
>>> set_power.voltage = 150
The Voltage value has to be either 120 or 240

>>> set_power.voltage = 120
>>> set_power.current = 10
>>> set_power.voltage
120
>>> set_power.current
10
To give example how bad it be look at this image
So the left side code refactor by me,right side try to write as in Java using Python.


RE: API REST Package for Calling/Flask - muzikman - Oct-22-2021

I looked at that image. That is some of the worst code I've seen. Your code is so much better. They set the dunder methods as class variables with all this get and set stuff.

You should never take control away from the user of your class. That entire if statement should have returned either a value or a boolean. Just kidding. :)