Python Forum
API REST Package for Calling/Flask
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
API REST Package for Calling/Flask
#11
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?
Reply
#12
(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.
Reply
#13
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. :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with return on REST API Flask korenron 0 1,314 Jun-13-2021, 10:40 AM
Last Post: korenron
  Calling Oracle REST SQL from Python johnjacob 2 2,036 Nov-05-2020, 04:19 AM
Last Post: johnjacob
  rest api parameter in flask bluefrog 3 3,282 Jun-21-2018, 05:03 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020