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

时间:2020-08-06 11:44:54

标签: java python

我正在将Java程序转换为python。在这里我被卡在一个地方,即吸气和塞特功能。 以下是Java代码,我必须将其转换为python代码。

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

1 个答案:

答案 0 :(得分:1)

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