在面向对象的编程中,我曾经有过这个问题而且我仍然这样做:
如果我们将为其创建一个公共getter和一个公共setter,那么将一个类成员声明为私有会有什么好处?
我认为上述案例与将类成员声明为公开的案件之间的安全级别没有任何区别.
谢谢!
为什么 - 或者为什么不 - 在Python OOP中专门使用getter和setter是一种好习惯?
我的教科书陈述如下:
import random
class Die(object):
"""Simulate a generic die."""
def __init__(self):
self.sides = 6
self.roll()
def roll(self):
"""Updates the die with a random roll."""
self.value = 1+random.randrange(self.sides)
return self.value
def getValue(self):
"""Return the last value set by roll()."""
return self.value
def main():
d1,d2 = Die(),Die()
for n in range(12):
print d1.roll(),d2.roll()
main()
Run Code Online (Sandbox Code Playgroud)
getValue()方法(称为getter或accessor)返回值实例变量的值.为什么要写这种功能?为什么不简单地使用实例变量?我们将在本章末尾的常见问题解答中解决这个问题.
但是,本章末尾没有FAQ,因此从未解释为什么在Python OOP中使用getter.
我曾尝试阅读其他地方,但我在任何地方都找不到好的解释.关于SO的大多数答案都是关于Java的,我读过它与Python无关 ......
有人可以帮助我理解为什么使用它们是好的做法?如果没有,为什么不呢?
我相对较新的Android编程(约2个月)是否有必要为几十个不同的变量获取?
例如 -
//Yes I realise that this isn't 'dozens'
public float getX() {
return position.x;
}
public float getY() {
return position.y;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public float getRotation() {
return rotation;
}
Run Code Online (Sandbox Code Playgroud)
虽然有必要为浮点数和字符串设置不同的getter和setter,但这是不好的做法,如果是这样,为什么要使用类似switch语句的东西来返回不同的变量?
public float returnSomething(String theThing) {
switch (theThing) {
case "height":
return height;
case "rotation" :
return rotation;
case "width":
return width;
default:
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
那么,上面的代码被认为是坏的吗?如果是这样,请解释原因.
感谢任何帮助,这不是一个真正的问题,因为无论哪种方式都运行正常,我只是不明白为什么人们会使用几十个getter和setter如果没有充分的理由.
我想同样的问题适用于制定者
我有一个简单的模型,我希望使用Spring JDBCTemplate在MySQL中保存这些实例.我使用DAO,使用简单的sql(insert into user(id, email...) value (:id, :email...))保存模型对象.是否有任何框架可以从模型中提取参数(当模型只是具有公共字段的POJO时).所以,我需要类似于Spring的东西BeanPropertySqlParameterSource,但是能够使用公共字段而不是属性.
模型类的示例:
public class User {
public int id;
public String email;
public String login;
public String password;
}
Run Code Online (Sandbox Code Playgroud)
我知道扩展AbstractSqlParameterSource可以解决我的问题,但我希望找到现有的框架.
UPD
实施基于AbstractSqlParameterSource:
public class PublicFieldsSqlParameterSource extends AbstractSqlParameterSource {
Map<String, Object> props = new HashMap<>();
public PublicFieldsSqlParameterSource(Object object) {
Field[] fields = object.getClass().getFields();
for (Field field : fields) {
String name = field.getName();
try {
Object value = field.get(object);
props.put(name, value);
} catch (IllegalAccessException ignored) { …Run Code Online (Sandbox Code Playgroud) 有人告诉我们应该避免使用限制器和吸气剂.关于它有各种各样的想法,但根据我使用这些打破封装.为什么?因为它告诉世界一个物体的内部.例如:
class Point {
private int x;
private int y;
void setx(int x) {...}
int getx() {...}
...
}
Run Code Online (Sandbox Code Playgroud)
该对象应该只暴露为客户端提供清晰抽象的行为.
class Point {
private int x;
private int y;
int coordinate(int x) {...} // 0, 1, 2, 3
...
}
Run Code Online (Sandbox Code Playgroud)
那么,这些存取器和setter方法是否打破了封装?
我想要做的是将我的类的一些实例存储在列表中,并从该列表中获取特定的实例.
这是自定义类的示例
public class Person
{
private String name;
//Several unrelevant fields here
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
//Several unrelevant methods here
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的代码,用于获取列表中的一个实例,即主类上的实例.
public class Main
{
private List<Person> people = new ArrayList<Person>();
//More unrelevant fields here
public Person getPerson(String name)
{
for (Person p : people)
if (p.getName().equalsIgnoreCase(name))
return p;
return null;
}
//More unrelevant methods here
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否有任何其他方法来写这个以提高性能.
public class Circle {
public float r = 100;
public float getR() {
return r;
}
}
public class GraphicCircle extends Circle {
public float r = 10;
public float getR() {
return r;
}
// Main method
public static void main(String[] args) {
GraphicCircle gc = new GraphicCircle();
Circle c = gc;
System.out.println("Radius = " + gc.r);
System.out.println("Radius = " + gc.getR());
System.out.println("Radius = " + c.r);
System.out.println("Radius = " + c.getR());
}
}
Run Code Online (Sandbox Code Playgroud)
嗨,我在理解上面代码的输出时遇到了麻烦。输出为:
Radius = 10.0
Radius …Run Code Online (Sandbox Code Playgroud) 我知道最好避免使用c ++中的宏.使用内联函数替换类似函数的宏,并使用constexpr/using来替换const-variable-define宏.但我想知道是否有一种方法可以通过一些现代的c ++技术取代宏连接功能.
例如,如何替换以下宏:
#define GETTER_AND_SETTER(name) \
inline void Set##name(int value) \
{ \
m_##name = value; \
}
inline int Get##name() const \
{ \
return m_##name; \
}
Run Code Online (Sandbox Code Playgroud)
然后在一个类中,我可以为很多变量做这个,这使得代码更加干净.
GETTER_AND_SETTER(Variable1)
GETTER_AND_SETTER(Variable2)
GETTER_AND_SETTER(Variable3)
...
Run Code Online (Sandbox Code Playgroud)
我在这里和这里检查过,但我没有得到答案.伙计们,对此有任何想法吗?谢谢.
编辑:getter/setter的例子只是用来表示想法.请不要专注于他们.:)
我正在编写一个编程项目列表,而这个项目是制作15个拼图(幻灯片拼图)的。当我遇到一个小障碍时,我正在从事该项目。
我的代码编译得很好,但是当我运行它时,在第12行出现了分段错误: pos[0] = x;
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Tile{
private:
vector<int> pos;
int value;
public:
Tile(int x, int y, int value_){
pos[0] = x;
pos[1] = y;
value = value_;
}
~Tile(){}
int getPos(int a){return pos[a];}
void setPos(int a, int b){pos[a] = b;}
};
int main(){
Tile tile1(1, 2, 10);
Tile* t1;
t1 = &tile1;
// returns position "x"
cout << t1->getPos(0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的意思是,我可以不必使用向量/数组来处理整个项目就可以完成整个项目,但是我仍然想知道,就我自己的理解而言,这为什么行不通。
基于我运行的调试,程序在初始化pos []向量的值时遇到了麻烦。
另一个问题:可能与此有关,我尝试在实例化矢量时设置其大小。
vector<int> pos(2); …
我可以用2种方式调用变量.
一个就是这样做:
MyClass myClass = new MyClass();
myLocalVar = myClass.myVarVal;
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用这样的getter:
myLocalVar = myClass.getMyVarVal();
Run Code Online (Sandbox Code Playgroud)
两种方式都运行良好,但我想知道最有效/最合适的方法是什么?
谢谢
java ×7
c++ ×3
oop ×3
getter ×2
android ×1
c++11 ×1
inheritance ×1
performance ×1
pointers ×1
python ×1
python-2.7 ×1
setter ×1
spring-jdbc ×1
vector ×1