codepro
codepro

Reputation: 313

How to pass setter property as argument to a function?

I am trying to pass a setter property as argument to a function. I have following properties for my class.

@property
def drawMode(self):
    return self._drawMode

@drawMode.setter
def drawMode(self, value):
    self._drawMode = value

I can pass the getter as an argument into a function as follows:

rectItem = CustGraphicsRectItem(rect, self.drawMode)

What is the syntax for passing the setter?

Upvotes: 5

Views: 3289

Answers (2)

c z
c z

Reputation: 8977

You can pass the property object directly and avoid magic strings. You still need to pass the instance:

class Class:
    def __init__( self ):
        self.__value = "old value"


    @property
    def value( self ):
        return self.__value


    @value.setter
    def value( self, value ):
        self.__value = value


def function( instance, property_ ):
    print( property_.fget( instance ) )
    property_.fset( instance, "new value" )
    print( property_.fget( instance ) )


instance = Class()
function( instance, Class.value )

Output:

old value
new value

Upvotes: 3

martineau
martineau

Reputation: 123463

You could do something like that if you pass the property's name to the function (along with the object itself). This allows the property object to be retrieved from the class of the object. Once that's obtained, its __set__() can be called directly.

class Test:
    def __init__(self):
        self._drawMode = None

    def foobar(self):
        pass

    @property
    def drawMode(self):
        return self._drawMode

    @drawMode.setter
    def drawMode(self, value):
        self._drawMode = value


def CustGraphicsRectItem(rect, obj, prop_name):
    obj_type = type(obj)
    if prop_name not in obj_type.__dict__:
        raise TypeError('{!r} is not an attribute of class {}'.format(
                            prop_name, obj_type.__name__))
    else:
        prop = obj_type.__dict__[prop_name]
        if not isinstance(prop, property):
            raise TypeError('{!r} is not an property of class {}'.format(
                                prop_name, obj_type.__name__))

    prop.__set__(obj, 42)  # Set property's value via direct call to setter.
    return rect

test = Test()
rect = [0, 0, 10, 20]
print(test.drawMode)  # -> None
rectItem = CustGraphicsRectItem(rect, test, 'drawMode')
print(test.drawMode)  # -< 42

Upvotes: 0

Related Questions