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

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

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.

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

答案1

得分: 2

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

class SomeClass:
    def __init__(self):
        self._abc = None

    @property
    def abc(self):
        return self._abc

    @abc.setter
    def abc(self, value):
        self._abc = value


obj = SomeClass()
obj.abc = 'test'
print(obj.abc)  # "test"

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

class SomeClass:
    def __init__(self):
        self.abc = None

obj = SomeClass()
obj.abc = 'test'
print(obj.abc)  # "test"

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

英文:

Python also has a property getter/setter mechanism:

class SomeClass:
    def __init__(self):
        self._abc = None

    @property
    def abc(self):
        return self._abc

    @abc.setter
    def abc(self, value):
        self._abc = value


obj = SomeClass()
obj.abc = 'test'
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:

class SomeClass:
    def __init__(self):
        self.abc = None

obj = SomeClass()
obj.abc = 'test'
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:

确定