对于python类使用“get函数”有什么好处? [英] What is the benefit to using a 'get function' for a python class?

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

问题描述

例如,在下面的代码中,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的兼容性,需要一组特定的方法可用。

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类使用“get函数”有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆