简体   繁体   English

获取 Python 属性的 setter 函数

[英]Getting the setter function of a Python property

I'm using a GUI module with an onchange parameter.我正在使用带有onchange参数的 GUI 模块。

Currently I have a Settings object that contains properties, and I want to bind them to my GUI.目前我有一个包含属性的Settings对象,我想将它们绑定到我的 GUI。

But my GUI only accepts setter functions , and not variables , so I need to get the setter function of my property.但是我的 GUI 只接受setter 函数,而不接受variables ,所以我需要获取我的属性的 setter 函数。

Here is the Settings code:这是Settings代码:

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:这是(简化的)GUI代码:

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)

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:只要做你在这种情况下会做的事情,不管有没有property

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM