OOP:getter/setter方法 [英] OOP: getter/setter methods
问题描述
因此,我读到您应该通过诸如object.get_this()
或object.set_that(value)
之类的getter/setter方法访问对象属性.该代码是否也适用于该类中定义的方法?或仅将它们与对象实例一起使用.例如,以这种方式这样做是惯用的,
So I've read that you're supposed to access object attributes through getter/setter methods like object.get_this()
or object.set_that(value)
. Does this code hold for methods that are also defined within the class? Or they are only meant to be used with object instances. For instance, is it idiomatic to do it this way,
class test:
def __init__(self,value):
self.value = value
def get_value(self):
return self.value
def method(self):
return some_operation(self.value)
定义了 用于访问对象实例的 with
在python中属性. In python do not use getter/setter methods. Instead just access the attribute itself, or, if you need code to be run every time the attribute is accessed or set, use properties. 这篇关于OOP:getter/setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!value
,还是应该在类方法中使用get_value()
?get_value()
defined for accessing value
for an object instance, or should get_value()
also be used within class methods?class test:
def __init__(self,value):
self.value = value
def get_value(self):
return self.value
def method(self):
return some_operation(self.get_value())
推荐答案