不同编程语言的getter和setter的使用 [英] The use of getters and setters for different programming languages

查看:176
本文介绍了不同编程语言的getter和setter的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道有很多关于getters和setters的问题,但是我找不到像我的问题。我想知道如果人们改变使用get / set取决于不同的语言。我开始学习C + +,并教会使用getter和setter。这是我的理解:

So I know there are a lot of questions on getters and setters in general, but I couldn't find something exactly like my question. I was wondering if people change the use of get/set depending on different languages. I started learning with C++ and was taught to use getters and setters. This is what I understand:

在C ++(和Java?),变量可以是公共的或私有的,但我们不能混合。例如,我不能有一个只读变量,仍然可以在类中更改。它或者是所有的公共的(可以读取和改变它),或者所有私人的(不能读,只能在类内部改变)。因为这个(和可能的其他原因),我们使用getter和setter。

In C++ (and Java?), a variable can either be public or private, but we cannot have a mix. For example, I can't have a read-only variable that can still be changed inside the class. It's either all public (can read and change it), or all private (can't read and can only change inside the class). Because of this (and possibly other reasons), we use getters and setters.

在MATLAB中,我可以控制变量的setaccess和getaccess我可以使事情只读(可以直接访问属性,但不能覆盖它)。在这种情况下,我不觉得我需要一个getter,因为我可以只做 class.property

In MATLAB, I can control the "setaccess" and "getaccess" properties of variables, so that I can make things read-only (can directly access the property, but can't overwrite it). In this case, I don't feel like I need a getter because I can just do class.property.

被认为是Pythonic不使用getters / setters,并且只有在需要时将东西放入属性。我真的不明白为什么它的所有公共变量在Python中,因为这与我在开始使用C ++时学到的相反。

Also, in Python it is considered "Pythonic" to not use getters/setters and to only put things into properties if needed. I don't really understand why its OK to have all public variables in Python, because that's opposite of what I learned when I started with C++.

我只是好奇其他人的想法在这。你会为所有语言使用getter和setters吗?你只能使用它为C ++ / Java和直接访问在MATLAB和Python(这是我现在正在做什么)?第二个选项被认为是坏的?为了我的目的,我只是指简单的getters和setters(只返回/设置值,不做任何其他操作)。

I'm just curious what other people's thoughts are on this. Would you use getters and setters for all languages? Would you only use it for C++/Java and do direct access in MATLAB and Python (which is what I am currently doing)? Is the second option considered bad? For my purposes, I am only referring to simple getters and setters (just return/set the value and do not do anything else).

谢谢! b $ b

推荐答案

实际上,getters和setter(以及隐藏这些的公共属性)对公共变量的改进非常小,并且是准类

Actually, getters and setters (as well as public properties hiding these) are very little improvement over public variables, and a pretty good indicator for quasi classes.

这篇关于不同编程语言的getter和setter的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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