我有一个带有两个类方法的类(使用classmethod()函数),用于获取和设置本质上是静态变量的类。我尝试使用property()函数来处理这些,但它会导致错误。我能够在解释器中重现以下错误:

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

我可以演示类方法,但它们不能作为属性:

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

是否可以使用属性()函数与@classmethod装饰函数?


当前回答

对于Python 3.9之前的函数式方法,您可以使用以下方法:

def classproperty(fget):
  return type(
      'classproperty',
      (),
      {'__get__': lambda self, _, cls: fget(cls), '__module__': None}
  )()
  
class Item:
  a = 47

  @classproperty
  def x(cls):
    return cls.a

Item.x

其他回答

这是我的解决方案,也缓存类属性

class class_property(object):
    # this caches the result of the function call for fn with cls input
    # use this as a decorator on function methods that you want converted
    # into cached properties

    def __init__(self, fn):
        self._fn_name = fn.__name__
        if not isinstance(fn, (classmethod, staticmethod)):
            fn = classmethod(fn)
        self._fn = fn

    def __get__(self, obj, cls=None):
        if cls is None:
            cls = type(obj)
        if (
            self._fn_name in vars(cls) and
            type(vars(cls)[self._fn_name]).__name__ != "class_property"
        ):
            return vars(cls)[self._fn_name]
        else:
            value = self._fn.__get__(obj, cls)()
            setattr(cls, self._fn_name, value)
            return value

是否可以使用属性()函数与类方法装饰函数?

No.

然而,类方法只是一个类的绑定方法(部分函数),可从该类的实例访问。

因为实例是类的一个函数,你可以从实例中派生类,你可以通过property从class-property中获得任何你想要的行为:

class Example(object):
    _class_property = None
    @property
    def class_property(self):
        return self._class_property
    @class_property.setter
    def class_property(self, value):
        type(self)._class_property = value
    @class_property.deleter
    def class_property(self):
        del type(self)._class_property

这段代码可以用来测试-它应该会通过而不会引发任何错误:

ex1 = Example()
ex2 = Example()
ex1.class_property = None
ex2.class_property = 'Example'
assert ex1.class_property is ex2.class_property
del ex2.class_property
assert not hasattr(ex1, 'class_property')

请注意,我们根本不需要元类——无论如何,您都不能通过类的实例直接访问元类。

编写@classproperty装饰器

你实际上可以通过子类化属性在几行代码中创建一个classproperty装饰器(它是在C中实现的,但你可以在这里看到等效的Python):

class classproperty(property):
    def __get__(self, obj, objtype=None):
        return super(classproperty, self).__get__(objtype)
    def __set__(self, obj, value):
        super(classproperty, self).__set__(type(obj), value)
    def __delete__(self, obj):
        super(classproperty, self).__delete__(type(obj))

然后将decorator视为结合了property的类方法:

class Foo(object):
    _bar = 5
    @classproperty
    def bar(cls):
        """this is the bar attribute - each subclass of Foo gets its own.
        Lookups should follow the method resolution order.
        """
        return cls._bar
    @bar.setter
    def bar(cls, value):
        cls._bar = value
    @bar.deleter
    def bar(cls):
        del cls._bar

这段代码应该没有错误:

def main():
    f = Foo()
    print(f.bar)
    f.bar = 4
    print(f.bar)
    del f.bar
    try:
        f.bar
    except AttributeError:
        pass
    else:
        raise RuntimeError('f.bar must have worked - inconceivable!')
    help(f)  # includes the Foo.bar help.
    f.bar = 5

    class Bar(Foo):
        "a subclass of Foo, nothing more"
    help(Bar) # includes the Foo.bar help!
    b = Bar()
    b.bar = 'baz'
    print(b.bar) # prints baz
    del b.bar
    print(b.bar) # prints 5 - looked up from Foo!

    
if __name__ == '__main__':
    main()

但我不确定这样做是否明智。一篇旧的邮件列表文章认为这种方法行不通。

让属性在类上工作:

上面的缺点是“class属性”不能从类中访问,因为它会简单地覆盖类__dict__中的数据描述符。

但是,我们可以用元类__dict__中定义的属性来覆盖它。例如:

class MetaWithFooClassProperty(type):
    @property
    def foo(cls):
        """The foo property is a function of the class -
        in this case, the trivial case of the identity function.
        """
        return cls

然后,元类的类实例可以有一个属性,使用前面已经演示过的原则访问类的属性:

class FooClassProperty(metaclass=MetaWithFooClassProperty):
    @property
    def foo(self):
        """access the class's property"""
        return type(self).foo

现在我们看到了两个例子

>>> FooClassProperty().foo
<class '__main__.FooClassProperty'>

这门课

>>> FooClassProperty.foo
<class '__main__.FooClassProperty'>

拥有对class属性的访问权。

这是我的建议。不要使用类方法。

认真对待。

在这种情况下使用类方法的原因是什么?为什么不使用普通类的普通对象呢?


如果你只是想改变值,属性并不是很有用,不是吗?只需要设置属性值就可以了。

只有在需要隐藏某些内容时才应该使用属性——这些内容在未来的实现中可能会改变。

也许你的例子被简化了,你漏掉了一些可怕的计算。但看起来这处房产并没有增加多少价值。

受java影响的“隐私”技术(在Python中,属性名以_开头)并不是很有用。谁的隐私?当您拥有源代码时,private的意义有点模糊(就像在Python中那样)。

受Java影响的ejb风格的getter和setter(通常在Python中作为属性完成)是为了方便Java的基本内省以及通过静态语言编译器的检查。所有这些getter和setter在Python中都没有那么有用。

对于Python 3.9之前的函数式方法,您可以使用以下方法:

def classproperty(fget):
  return type(
      'classproperty',
      (),
      {'__get__': lambda self, _, cls: fget(cls), '__module__': None}
  )()
  
class Item:
  a = 47

  @classproperty
  def x(cls):
    return cls.a

Item.x

基于https://stackoverflow.com/a/1800999/2290820


class MetaProperty(type):

    def __init__(cls, *args, **kwargs):
        super()

    @property
    def praparty(cls):
        return cls._var

    @praparty.setter
    def praparty(cls, val):
        cls._var = val


class A(metaclass=MetaProperty):
    _var = 5


print(A.praparty)
A.praparty = 6
print(A.praparty)