本文介绍了在Python中定义属性的首选方式:属性装饰器或lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中定义类属性的首选方式是什么?为什么?可以同时使用这两种方法吗?
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?
@property
def total(self):
return self.field_1 + self.field_2
或
total = property(lambda self: self.field_1 + self.field_2)
推荐答案
在您想要将方法转换为只读属性的情况下,装饰器形式可能是最好的。如果您想同时提供一个setter / deleter / docstring以及getter,或者想为其属性添加一个名称不同的属性,则第二种情况会更好。
The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value from.
这篇关于在Python中定义属性的首选方式:属性装饰器或lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!