gpt4 book ai didi

python - 提高属性(property)装饰师的绩效?

转载 作者:行者123 更新时间:2023-12-01 01:16:39 25 4
gpt4 key购买 nike

我尝试理解和使用属性装饰器主要是为了使属性只读。我看到,每次使用该属性时,它都会进入属性装饰器。

在我的示例中,它进入装饰器三次,每次打印一次:

class PropTest:

def __init__(self,x):
self._x = x

@property
def x(self):
return self._x

def check(self):
print(self.x + 1)
print(self.x + 2)
print(self.x + 3)

t = PropTest(3)
t.check()

如果我在__init__中定义属性,它只会输入一次。

class PropTest:

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

def check(self):
print(self.x + 1)
print(self.x + 2)
print(self.x + 3)

t = PropTest(3)
t.check()

我是否以错误的方式使用装饰器?我使用时有性能问题吗?

L.E. :

这就是我尝试使用属性装饰器的方式。我不想每次使用该属性时都读取 Excel,并且我希望数据框是只读的。

@property
def rules_df(self):
"""
:return: A dataframe that contains the rules for labels
"""
self._rules_df = pd.read_excel(self.cfg_file)
return self._rules_df

最佳答案

您在第一个示例中正确使用了该属性。在第二个示例中,您没有使用属性,而只是设置对象的成员。

属性只是使方法像字段一样的语法糖。

性能可能会受到轻微影响。通常无需担心。

如果要设置属性的值this Q/A on SO可能有帮助。

关于python - 提高属性(property)装饰师的绩效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54286596/

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