classproperty公司#

class astropy.utils.decorators.classproperty(fget=None, doc=None, lazy=False)[源代码]#

基类:property

类似 property ,但允许类级属性。也就是说,其getter类似于 classmethod .

包装的方法可以显式使用 classmethod decorator(必须在这个decorator之前),或者 classmethod 可以省略(通过使用这个修饰符是隐式的)。

备注

classproperty仅适用于 read-only 属性。由于Python描述符工作方式的微妙之处,它目前不允许写/删除属性。为了在类上实现这样的属性,必须实现该类的元类。

参数:
fget : callable()Python:Callable()

计算此属性值的函数(特别是用作装饰器时的函数)为la property .

doc : str ,可选Python:字符串,可选

属性的docstring——默认情况下继承自getter函数。

lazy : bool ,可选可选的布尔

如果为True,则缓存第一次调用getter函数返回的值,以便只调用一次(用于延迟计算属性)。这类似于 lazyproperty . 这个 lazy 参数也可以在以下情况下使用 classproperty 用作装饰器(参见下面的第三个示例)。在decorator语法中使用时 must 作为关键字参数传入。

实例

>>> class Foo:
...     _bar_internal = 1
...     @classproperty
...     def bar(cls):
...         return cls._bar_internal + 1
...
>>> Foo.bar
2
>>> foo_instance = Foo()
>>> foo_instance.bar
2
>>> foo_instance._bar_internal = 2
>>> foo_instance.bar  # Ignores instance attributes
2

如前所述,a classproperty 仅限于实现只读属性:

>>> class Foo:
...     _bar_internal = 1
...     @classproperty
...     def bar(cls):
...         return cls._bar_internal
...     @bar.setter
...     def bar(cls, value):
...         cls._bar_internal = value
...
Traceback (most recent call last):
...
NotImplementedError: classproperty can only be read-only; use a
metaclass to implement modifiable class-level properties

lazy 选项时,getter只调用一次::

>>> class Foo:
...     @classproperty(lazy=True)
...     def bar(cls):
...         print("Performing complicated calculation")
...         return 1
...
>>> Foo.bar
Performing complicated calculation
1
>>> Foo.bar
1

如果子类继承lazy classproperty 仍为子类重新计算属性::

>>> class FooSub(Foo):
...     pass
...
>>> FooSub.bar
Performing complicated calculation
1
>>> FooSub.bar
1

方法总结

deleter \(fdel)

描述符,以获取具有不同删除器的属性副本。

getter \(fget)

描述符,以获取具有不同获取方法的属性副本。

setter \(fset)

描述符以获取具有不同设置器的属性副本。

方法文件

deleter(fdel)[源代码]#

描述符,以获取具有不同删除器的属性副本。

getter(fget)[源代码]#

描述符,以获取具有不同获取方法的属性副本。

setter(fset)[源代码]#

描述符以获取具有不同设置器的属性副本。