本文介绍了对 python 类使用“获取函数"有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在下面的代码中,getName 函数的好处是什么?

For example, in the code below, what is the benefit of the getName function?

class Node(object):
    def __init__(self, name):
        self.name = str(name)
    def getName(self):
        return self.name
    def __str__(self):
        return self.name

推荐答案

没有任何好处.从其他语言(例如 Java)开始使用 Python 的人有时会这样做,因为他们已经习惯了.在 Python 中,创建这些类型的 getter 和 setter 没有任何意义,它们除了直接获取和设置底层变量之外什么都不做.属性允许您在以后需要做一些更复杂的事情时透明地交换逻辑不仅仅是获取/设置值.

There is no benefit. People coming to Python from other languages (e.g., Java) sometimes do this because they're used to it. In Python there is no point to creating these sorts of getters and setters that don't do anything but directly get and set the underlying variable. Properties allow you to transparently swap in logic if at a later time you need to do something more complex than just get/set the value.

使用 getter/setter 可能有好处,但在 Python 中,没有真正的理由使用简单的 getter/setter 而不是直接获取/设置属性.我能想到的唯一原因是,如果您必须保持与现有 API 的兼容性,该 API 需要一组特定的方法可用.

There can be a benefit in using getters/setters, but in Python there is no real reason to use trivial getters/setters instead of just getting/setting the attribute directly. The only reason I can think of would be if you have to maintain compatibility with an existing API that requires a certain set of methods to be available.

这篇关于对 python 类使用“获取函数"有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:42