gpt4 book ai didi

python - python 中的专用@property 装饰器

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:08 25 4
gpt4 key购买 nike

我有几个类,每个类都有一些属性。所有属性的共同点是它们应该是数字属性。这似乎是使用 python 装饰器的理想场所,但我似乎无法确定正确的实现方式是什么。这是一个简单的例子:

class Junk(object):
def __init__(self, var):
self._var = var

@property
def var(self):
"""A numeric variable"""
return self._var

@var.setter
def size(self, value):
# need to make sure var is an integer
if not isinstance(value, int):
raise ValueError("var must be an integer, var = {}".format(value))
self._var = value

@var.deleter
def size(self):
raise RuntimeError("You can't delete var")

在我看来,应该可以编写一个装饰器来完成所有事情,以便将上面的内容转换为:

def numeric_property(*args, **kwargs):
...

class Junk(object):
def __init__(self, var):
self._var = var

@numeric_property
def var(self):
"""A numeric variable"""
return self._var

这样新的 numeric_property 装饰器可以在许多类中使用。

最佳答案

@property 只是 Python 的 descriptor protocol 的一个特例,因此您当然可以构建自己的自定义版本。对于您的情况:

class NumericProperty:
"""A property that must be numeric.

Args:
attr (str): The name of the backing attribute.

"""

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

def __get__(self, obj, type=None):
return getattr(obj, self.attr)

def __set__(self, obj, value):
if not isinstance(value, int):
raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value))
setattr(obj, self.attr, value)

def __delete__(self, obj):
raise RuntimeError("You can't delete {}".format(self.attr))

class Junk:

var = NumericProperty('_var')

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

正在使用中:

>>> j = Junk('hi')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jonrsharpe/test.py", line 29, in __init__
self.var = var
File "/Users/jonrsharpe/test.py", line 17, in __set__
raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value))
ValueError: _var must be an integer, var = 'hi'
>>> j = Junk(1)
>>> del j.var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jonrsharpe/test.py", line 21, in __delete__
raise RuntimeError("You can't delete {}".format(self.attr))
RuntimeError: You can't delete _var
>>> j.var = 'hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jonrsharpe/test.py", line 17, in __set__
raise ValueError("{} must be an integer, var = {!r}".format(self.attr, value))
ValueError: _var must be an integer, var = 'hello'
>>> j.var = 2
>>> j.var
2

关于python - python 中的专用@property 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39539292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com