基本上我想做这样的事情:
class foo:
x = 4
@property
@classmethod
def number(cls):
return x
然后我希望以下工作:
>>> foo.number
4
不幸的是,上述方法无效。而不是给我4
它给了我<property object at 0x101786c58>
。有没有办法实现上述目标?
答案 0 :(得分:61)
这会使Foo.number
成为只读属性:
class MetaFoo(type):
@property
def number(cls):
return cls.x
class Foo(object, metaclass=MetaFoo):
x = 4
print(Foo.number)
# 4
Foo.number = 6
# AttributeError: can't set attribute
解释:使用@property时的常见情况如下:
class Foo(object):
@property
def number(self):
...
foo = Foo()
Foo
中定义的属性对于其实例是只读的。也就是说,foo.number = 6
会引发AttributeError
。
类似地,如果您希望Foo.number
引发AttributeError
,则需要设置type(Foo)
中定义的属性。因此需要一个元类。
请注意,此只读权不受黑客的影响。 通过更改Foo,可以使该属性可写 类:
class Base(type): pass
Foo.__class__ = Base
# makes Foo.number a normal class attribute
Foo.number = 6
print(Foo.number)
打印
6
或者,如果您希望Foo.number
设置可设置的属性,
class WritableMetaFoo(type):
@property
def number(cls):
return cls.x
@number.setter
def number(cls, value):
cls.x = value
Foo.__class__ = WritableMetaFoo
# Now the assignment modifies `Foo.x`
Foo.number = 6
print(Foo.number)
还打印6。
答案 1 :(得分:40)
property
描述符在从类访问时总是返回自身(即instance
None
方法__get__
时{。}}。
如果那不是您想要的,您可以编写一个始终使用类对象(owner
)而不是实例的新描述符:
>>> class classproperty(object):
... def __init__(self, getter):
... self.getter= getter
... def __get__(self, instance, owner):
... return self.getter(owner)
...
>>> class Foo(object):
... x= 4
... @classproperty
... def number(cls):
... return cls.x
...
>>> Foo().number
4
>>> Foo.number
4
答案 2 :(得分:15)
我同意unubtu's answer;它似乎工作,但是,它不适用于 Python 3 上的这种精确语法(具体来说,Python 3.4就是我所挣扎的)。以下是在Python 3.4下必须形成模式以使事情有效的方法,似乎是:
class MetaFoo(type):
@property
def number(cls):
return cls.x
class Foo(metaclass=MetaFoo):
x = 4
print(Foo.number)
# 4
Foo.number = 6
# AttributeError: can't set attribute
答案 3 :(得分:7)
米哈伊尔·格拉西莫夫的解决方案非常完整。不幸的是,这是一个缺点。如果你有一个使用他的classproperty的类,那么没有子类可以使用它
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
与class Wrapper
。
幸运的是,这可以修复。在创建class Meta
时,只需继承给定类的元类。
def classproperty_support(cls):
"""
Class decorator to add metaclass to our class.
Metaclass uses to add descriptors to class attributes, see:
http://stackoverflow.com/a/26634248/1113207
"""
# Use type(cls) to use metaclass of given class
class Meta(type(cls)):
pass
for name, obj in vars(cls).items():
if isinstance(obj, classproperty):
setattr(Meta, name, property(obj.fget, obj.fset, obj.fdel))
class Wrapper(cls, metaclass=Meta):
pass
return Wrapper
答案 4 :(得分:6)
上述解决方案的问题在于它无法从实例变量访问类变量:
print(Foo.number)
# 4
f = Foo()
print(f.number)
# 'Foo' object has no attribute 'number'
此外,使用metaclass explicit并不如使用常规property
装饰器那么好。
我试图解决这个问题。现在它是如何运作的:
@classproperty_support
class Bar(object):
_bar = 1
@classproperty
def bar(cls):
return cls._bar
@bar.setter
def bar(cls, value):
cls._bar = value
# @classproperty should act like regular class variable.
# Asserts can be tested with it.
# class Bar:
# bar = 1
assert Bar.bar == 1
Bar.bar = 2
assert Bar.bar == 2
foo = Bar()
baz = Bar()
assert foo.bar == 2
assert baz.bar == 2
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50
如您所见,对于类变量,我们@classproperty
与@property
的工作方式相同。我们唯一需要的是额外的@classproperty_support
类装饰器。
解决方案也适用于只读类属性。
这是实施:
class classproperty:
"""
Same as property(), but passes obj.__class__ instead of obj to fget/fset/fdel.
Original code for property emulation:
https://docs.python.org/3.5/howto/descriptor.html#properties
"""
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj.__class__)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj.__class__, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj.__class__)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
def classproperty_support(cls):
"""
Class decorator to add metaclass to our class.
Metaclass uses to add descriptors to class attributes, see:
http://stackoverflow.com/a/26634248/1113207
"""
class Meta(type):
pass
for name, obj in vars(cls).items():
if isinstance(obj, classproperty):
setattr(Meta, name, property(obj.fget, obj.fset, obj.fdel))
class Wrapper(cls, metaclass=Meta):
pass
return Wrapper
注意:代码测试不多,请随时注意它是否无法正常工作。