在classmethods上使用property()

问题描述 投票:148回答:13

我有一个类有两个类方法(使用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

是否可以将property()函数与classmethod修饰函数一起使用?

python oop
13个回答
71
投票

在类上创建属性但影响实例。因此,如果您需要classmethod属性,请在元类上创建属性。

>>> class foo(object):
...     _var = 5
...     class __metaclass__(type):  # Python 2 syntax for metaclasses
...         pass
...     @classmethod
...     def getvar(cls):
...         return cls._var
...     @classmethod
...     def setvar(cls, value):
...         cls._var = value
...     
>>> foo.__metaclass__.var = property(foo.getvar.im_func, foo.setvar.im_func)
>>> foo.var
5
>>> foo.var = 3
>>> foo.var
3

但是因为你无论如何都在使用元类,如果只是在那里移动类方法,它会更好。

>>> class foo(object):
...     _var = 5
...     class __metaclass__(type):  # Python 2 syntax for metaclasses
...         @property
...         def var(cls):
...             return cls._var
...         @var.setter
...         def var(cls, value):
...             cls._var = value
... 
>>> foo.var
5
>>> foo.var = 3
>>> foo.var
3

或者,使用Python 3的metaclass=...语法,以及在foo类体外定义的元类,以及负责设置_var初始值的元类:

>>> class foo_meta(type):
...     def __init__(cls, *args, **kwargs):
...         cls._var = 5
...     @property
...     def var(cls):
...         return cls._var
...     @var.setter
...     def var(cls, value):
...         cls._var = value
...
>>> class foo(metaclass=foo_meta):
...     pass
...
>>> foo.var
5
>>> foo.var = 3
>>> foo.var
3

1
投票

尝试一下,无需更改/添加大量现有代码即可完成工作。

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

property函数需要两个callable参数。给他们lambda包装器(它将实例作为第一个参数传递)并且一切都很好。


1
投票

这是一个解决方案,它既可以通过类访问,也可以通过使用元类的实例进行访问。

In [1]: class ClassPropertyMeta(type):
   ...:     @property
   ...:     def prop(cls):
   ...:         return cls._prop
   ...:     def __new__(cls, name, parents, dct):
   ...:         # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable
   ...:         dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))
   ...:         dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))
   ...:         return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)
   ...:

In [2]: class ClassProperty(object):
   ...:     __metaclass__ = ClassPropertyMeta
   ...:     _prop = 42
   ...:     def __getattr__(self, attr):
   ...:         raise Exception('Never gets called')
   ...:

In [3]: ClassProperty.prop
Out[3]: 42

In [4]: ClassProperty.prop = 1
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-e2e8b423818a> in <module>()
----> 1 ClassProperty.prop = 1

AttributeError: can't set attribute

In [5]: cp = ClassProperty()

In [6]: cp.prop
Out[6]: 42

In [7]: cp.prop = 1
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-e8284a3ee950> in <module>()
----> 1 cp.prop = 1

<ipython-input-1-16b7c320d521> in <lambda>(cls, attr, val)
      6         # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable
      7         dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))
----> 8         dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))
      9         return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)

AttributeError: can't set attribute

这也适用于元类中定义的setter。


0
投票

在搜索了不同的地方之后,我找到了一种方法来定义一个有效的Python 2和3的classproperty。

from future.utils import with_metaclass

class BuilderMetaClass(type):
    @property
    def load_namespaces(self):
        return (self.__sourcepath__)

class BuilderMixin(with_metaclass(BuilderMetaClass, object)):
    __sourcepath__ = 'sp'        

print(BuilderMixin.load_namespaces)

希望这可以帮助别人:)


-18
投票

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

认真。

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


如果你只是想改变价值,一个属性真的不是很有帮助吗?只需设置属性值即可完成。

只有在隐藏某些东西时才应使用属性 - 这可能会在将来的实现中发生变化。

也许你的例子被剥夺了,并且你已经离开了一些地狱般的计算。但它看起来并不像物业增加了重要价值。

受Java影响的“隐私”技术(在Python中,以_开头的属性名称)并不是非常有用。私人是谁?当你拥有源代码时,私有点有点模糊(就像在Python中一样。)

受Java影响的EJB样式的getter和setter(通常在Python中作为属性完成)可以促进Java的原始内省以及通过静态语言编译器。所有这些getter和setter在Python中都没那么有用。


69
投票

阅读Python 2.2 release笔记,我发现以下内容。

当属性作为类属性(C.x)而不是实例属性(C()。x)访问时,将不会调用[属性]的get方法。如果要在用作类属性时覆盖属性的__get__操作,则可以子类化属性 - 它本身是新样式类型 - 以扩展其__get__方法,或者您可以通过创建新的方法从头开始定义描述符类型-style类定义__get __,__ set__和__delete__方法。

注意:以下方法实际上不适用于setter,只适用于getter。

因此,我认为规定的解决方案是创建一个ClassProperty作为属性的子类。

class ClassProperty(property):
    def __get__(self, cls, owner):
        return self.fget.__get__(None, owner)()

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=ClassProperty(getvar,setvar)

assert foo.getvar() == 5
foo.setvar(4)
assert foo.getvar() == 4
assert foo.var == 4
foo.var = 3
assert foo.var == 3

但是,setter实际上并不起作用:

foo.var = 4
assert foo.var == foo._var # raises AssertionError

foo._var没有变化,您只是用新值覆盖了该属性。

你也可以使用ClassProperty作为装饰者:

class foo(object):
    _var = 5

    @ClassProperty
    @classmethod
    def var(cls):
        return cls._var

    @var.setter
    @classmethod
    def var(cls, value):
        cls._var = value

assert foo.var == 5

45
投票

我希望这个死简单的只读@classproperty装饰器可以帮助某人寻找classproperties。

class classproperty(object):

    def __init__(self, fget):
        self.fget = fget

    def __get__(self, owner_self, owner_cls):
        return self.fget(owner_cls)

class C(object):

    @classproperty
    def x(cls):
        return 1

assert C.x == 1
assert C().x == 1

21
投票

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

没有。

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

由于实例是类的函数,并且您可以从实例派生类,因此您可以使用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 property),在几行代码中创建一个here装饰器:

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

然后将装饰器视为与属性结合的类方法:

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

但我不确定这会是多么明智。一个旧的邮件列表article建议它不应该工作。

让财产在班上工作:

上面的缺点是无法从类中访问“类属性”,因为它只会覆盖类__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'>

有权访问类属性。


17
投票

Python 3!

老问题,很多观点,非常需要一个真正的Python 3方式。

幸运的是,使用metaclass kwarg很容易:

class FooProperties(type):

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

class Foo(object, metaclass=FooProperties):
    _var = 'FOO!'

然后,>>> Foo.var

'FOO!'


15
投票

没有合理的方法可以使这个“类属性”系统在Python中运行。

这是让它发挥作用的一种不合理的方法。随着元类魔法数量的增加,你当然可以使它更加无缝。

class ClassProperty(object):
    def __init__(self, getter, setter):
        self.getter = getter
        self.setter = setter
    def __get__(self, cls, owner):
        return getattr(cls, self.getter)()
    def __set__(self, cls, value):
        getattr(cls, self.setter)(value)

class MetaFoo(type):
    var = ClassProperty('getvar', 'setvar')

class Foo(object):
    __metaclass__ = MetaFoo
    _var = 5
    @classmethod
    def getvar(cls):
        print "Getting var =", cls._var
        return cls._var
    @classmethod
    def setvar(cls, value):
        print "Setting var =", value
        cls._var = value

x = Foo.var
print "Foo.var = ", x
Foo.var = 42
x = Foo.var
print "Foo.var = ", x

问题的结点是属性是Python所谓的“描述符”。没有简单易行的方法来解释这种元编程是如何工作的,所以我必须指向descriptor howto

如果要实现相当高级的框架,您只需要了解这类事情。像透明对象持久性或RPC系统,或一种特定于域的语言。

但是,在对先前答案的评论中,您说是您

需要修改一个属性,该属性以类的所有实例所看到的方式进行修改,并且在调用这些类方法的范围内不会引用该类的所有实例。

在我看来,你真正想要的是一个Observer设计模式。


5
投票

如果要通过实例化对象访问类属性,则仅在元类上进行设置无效,在这种情况下,您还需要在对象上安装普通属性(调度到类属性)。我认为以下内容更为明确:

#!/usr/bin/python

class classproperty(property):
    def __get__(self, obj, type_):
        return self.fget.__get__(None, type_)()

    def __set__(self, obj, value):
        cls = type(obj)
        return self.fset.__get__(None, cls)(value)

class A (object):

    _foo = 1

    @classproperty
    @classmethod
    def foo(cls):
        return cls._foo

    @foo.setter
    @classmethod
    def foo(cls, value):
        cls.foo = value

a = A()

print a.foo

b = A()

print b.foo

b.foo = 5

print a.foo

A.foo = 10

print b.foo

print A.foo

2
投票

半个解决方案,__set__在课堂上仍然不起作用。解决方案是一个实现属性和静态方法的自定义属性类

class ClassProperty(object):
    def __init__(self, fget, fset):
        self.fget = fget
        self.fset = fset

    def __get__(self, instance, owner):
        return self.fget()

    def __set__(self, instance, value):
        self.fset(value)

class Foo(object):
    _bar = 1
    def get_bar():
        print 'getting'
        return Foo._bar

    def set_bar(value):
        print 'setting'
        Foo._bar = value

    bar = ClassProperty(get_bar, set_bar)

f = Foo()
#__get__ works
f.bar
Foo.bar

f.bar = 2
Foo.bar = 3 #__set__ does not

2
投票

因为我需要以一种类的所有实例看到的方式修改一个属性,并且在调用这些类方法的范围内没有对该类的所有实例的引用。

您是否可以访问该类的至少一个实例?我可以想到一种方法来做到这一点:

class MyClass (object):
    __var = None

    def _set_var (self, value):
        type (self).__var = value

    def _get_var (self):
        return self.__var

    var = property (_get_var, _set_var)

a = MyClass ()
b = MyClass ()
a.var = "foo"
print b.var
© www.soinside.com 2019 - 2024. All rights reserved.