我正在尝试将Java代码转换为Python代码。

huangapple go评论112阅读模式
英文:

I am trying to covert java codes into python code

问题

public String getABC() {
return ABC;
}

public void setABC(String ABC) {
this.ABC = ABC;
}

英文:

I am converting Java program to python. here i am stuck at one place ie getter and setter function.
the java code is following, i have to convert it into python code.

  1. public String getABC() {
  2. return ABC;
  3. }
  4. public void setABC(String ABC) {
  5. this.ABC = ABC;
  6. }

答案1

得分: 2

Python 也有一个属性获取器/设置器机制:

  1. class SomeClass:
  2. def __init__(self):
  3. self._abc = None
  4. @property
  5. def abc(self):
  6. return self._abc
  7. @abc.setter
  8. def abc(self, value):
  9. self._abc = value
  10. obj = SomeClass()
  11. obj.abc = 'test'
  12. print(obj.abc) # "test"

但值得注意的是,只有当您需要控制对受保护属性的访问或在获取或设置值时执行其他操作时,这种方法才有意义。否则,直接在构造函数中初始化属性并直接使用它会更简单:

  1. class SomeClass:
  2. def __init__(self):
  3. self.abc = None
  4. obj = SomeClass()
  5. obj.abc = 'test'
  6. print(obj.abc) # "test"

这个教程应该对您有所帮助:https://www.python-course.eu/python3_properties.php。

英文:

Python also has a property getter/setter mechanism:

  1. class SomeClass:
  2. def __init__(self):
  3. self._abc = None
  4. @property
  5. def abc(self):
  6. return self._abc
  7. @abc.setter
  8. def abc(self, value):
  9. self._abc = value
  10. obj = SomeClass()
  11. obj.abc = 'test'
  12. print(obj.abc) # "test"

But it's worth noting that this approach would make sense only if you need to control access to a protected property or to perform additional operations while getting or setting the value. Otherwise, it would be more straightforward to initialise a property in the constructor and use it directly:

  1. class SomeClass:
  2. def __init__(self):
  3. self.abc = None
  4. obj = SomeClass()
  5. obj.abc = 'test'
  6. print(obj.abc) # "test"

This tutorial should help you: https://www.python-course.eu/python3_properties.php.

huangapple
  • 本文由 发表于 2020年8月6日 19:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63282883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定