Using property() on classmethods

后端 未结 15 940
Happy的楠姐
Happy的楠姐 2020-11-22 16:55

I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() functi

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 17:43

    Give this a try, it gets the job done without having to change/add a lot of existing code.

    >>> class foo(object):
    ...     _var = 5
    ...     def getvar(cls):
    ...         return cls._var
    ...     getvar = classmethod(getvar)
    ...     def setvar(cls, value):
    ...         cls._var = value
    ...     setvar = classmethod(setvar)
    ...     var = property(lambda self: self.getvar(), lambda self, val: self.setvar(val))
    ...
    >>> f = foo()
    >>> f.var
    5
    >>> f.var = 3
    >>> f.var
    3
    

    The property function needs two callable arguments. give them lambda wrappers (which it passes the instance as its first argument) and all is well.

提交回复
热议问题