Python Forum

Full Version: Calling functions by making part of their name with variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am new to python and programming in general.

I have the following 4 functions:
  • __scroll_down
  • __scroll_up
  • __scroll_left
  • __scroll_right

I also have a variable called direction which can contain either: down, up, left or right

Is there a way to call a function based on the variable name, maybe something like this __scroll_{direction}() ?

Thank you for your time and help
Crouz
Use a dictionary
scroll = {
    'down': __scroll_down,
    'left': __scroll_left,
    'right': __scroll_right,
    'up': __scroll_up,
}
scroll['up']()
What is the purpose of the double underscores?
You could also define a function
scroll_dispatch = {
    'down': __scroll_down,
    'left': __scroll_left,
    'right': __scroll_right,
    'up': __scroll_up,
}
def scroll(direction):
    return scroll_dispatch[direction]()

scroll('up')
Depending on what your __scroll_xx functions is doing, you may want to have only one function named "scroll" and provide te direction as an argument to the function.

And what is the purpose of the double underscores here?

Regards, noisefoor
Thank you all for your answers.

Double underscores mean these class methods are private and can only be called within that class or its instances
(Nov-02-2023, 10:59 AM)crouzilles Wrote: [ -> ]Double underscores mean these class methods are private and can only be called within that class or its instances
That's wrong. Python doesn't know anything like private / protected methods. If a method or attribute shouldn't be accessed from the outside it is marked by convention with a single leading underscore. However, this is a _convention_ it's still accessible.
A double leading underscore will make Python do some name mangling when an instance of the class is created. However, the method or attribute is still accessible. The real world use cases for double leading underscore are more on the rare side.

For a deeper explanation with examples you may want to read e.g. this article about the meaning of underscores in Python code.

Regards, noisefloor