Search code examples
pythonclasssetter

Return a way to set a property of a class


So I have the following function:

class Test:
    def __init__(self):
        self.test = False

def test():
    test = Test()
    # And now return some way to set the test.test property

So I would like the test function to return some way to set test.test

I tried the following things:

def test():
    test = Test()
    return test.test

property = test()
property = True
# Doesn't work, doesn't pass a reference

Or what could work (but )

def test():
    test = Test()
    def set(to):
        test.test = to
    return set

fnc = test()
# But how do i execute it then

Of course, it would also be possible to just return the "test" object, but I don't want that because then the other properties of the Test object can then also be changed


Solution

  • class Test:
        def __init__(self):
            self.test = False
    
    def test():
        test = Test()
        def set_test(val: bool):
            test.test = val
        return set_test
    
    test()(True)  # test.test is now True... somewhere!
    

    Note that a problem with this is that while you have a function that lets you change test.test, you don't actually have access to the test object to see whether it worked.

    If you want to make the test.test value accessible without making the enclosing test object accessible, you could return a getter as well as a setter:

    from typing import Callable, Tuple
    
    
    class Test:
        def __init__(self):
            self.test = False
    
    
    def test() -> Tuple[Callable[[], bool], Callable[[bool], None]]:
        test = Test()
    
        def get_test() -> bool:
            return test.test
    
        def set_test(val: bool) -> None:
            test.test = val
    
        return get_test, set_test
    
    
    get_test, set_test = test()
    print(get_test())  # False
    set_test(True)
    print(get_test())  # True