Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the setter function of a Python property

I’m using a GUI module with an onchange parameter.

Currently I have a Settings object that contains properties, and I want to bind them to my GUI.

But my GUI only accepts setter functions, and not variables, so I need to get the setter function of my property.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the Settings code:

class Settings:
    def __init__(self):
        self._name = "Jhon Doe"

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if value.count(" ") > 1:
            self._name = value

Here is the (simplified) GUI code:

import pygame
import pygame_menu
from settings import Settings

settings = Settings()

pygame.init()
surface = pygame.display.set_mode((600, 600))

menu = pygame_menu.Menu('My menu', 600, 600)

menu.add.text_input('Name :', default='John Doe', onchange=settings.name)
menu.add.button('Quit', pygame_menu.events.EXIT)
menu.mainloop(surface)

>Solution :

You don’t need the actual function, that is written as a method so it requires the instance. Just do what you’d do in this situation, whether there were a property or not:

def _callback(value):
    settings.name = value

menu.add.text_input('Name :', default='John Doe', onchange=_callback)

Or, alternatively,

menu.add.text_input('Name :', default='John Doe', onchange=lambda value: setattr(settings, "name", value))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading