[Python] Using property() on classmethods

Discussão em 'Python' iniciado por Stack, Abril 19, 2025.

  1. Stack

    Stack Membro Participativo

    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() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:

    class Foo(object):
    _var = 5
    @classmethod
    def getvar(cls):
    return cls._var
    @classmethod
    def setvar(cls, value):
    cls._var = value
    var = property(getvar, setvar)


    I can demonstrate the class methods, but they don't work as properties:

    >>> f = Foo()
    >>> f.getvar()
    5
    >>> f.setvar(4)
    >>> f.getvar()
    4
    >>> f.var
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: 'classmethod' object is not callable
    >>> f.var=5
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: 'classmethod' object is not callable


    Is it possible to use the property() function with @classmethod decorated functions?

    Continue reading...

Compartilhe esta Página