英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论