gpt4 book ai didi

python - 为继承设计时为什么是 "use properties to hide functional implementation"?

转载 作者:行者123 更新时间:2023-12-04 18:02:27 24 4
gpt4 key购买 nike

下面是一个paragraph in PEP8 .我不明白“在那种情况下,使用属性将功能实现隐藏在简单的数据属性访问语法后面。”和注释 3:

For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

Note 1: Properties only work on new-style classes.

Note 2: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.

Note 3: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

最佳答案

隐藏实现的目标是保持 API 不变。

如果您设计了一个带有简单属性的类,后来发现子类需要计算才能返回正确的值,您只需将简单属性替换为计算属性即可,相关 API 保持不变。计算属性更广为人知的是属性。

注意 3 是在设计类时要牢记的建议,而不是在子类化时。

关于python - 为继承设计时为什么是 "use properties to hide functional implementation"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805022/

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