2011-11-28 67 views
20

所以我读过你应该通过像object.get_this()object.set_that(value)这样的getter/setter方法来访问对象属性。此代码是否适用于在该类中定义的方法?或者它们只能用于对象实例。比如,是不是习惯去做这样,OOP:getter/setter方法

class test: 
    def __init__(self,value): 
     self.value = value 
    def get_value(self): 
     return self.value 
    def method(self): 
     return some_operation(self.value) 

get_value()访问value对象实例定义,还是应该get_value()也类方法中使用?

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()) 
+4

检查“property”内置函数:http://docs.python.org/library/functions.html#property – eumiro

+3

我不知道你在哪里读过这个,但我敢打赌不在任何Python上下文中。在Python中,情况正好相反。 –

回答

46

在python do not use getter/setter methods。相反,只需访问属性本身,或者如果您需要在每次访问或设置属性时运行代码,请使用properties

+19

+1这样做的其他原因:[Python不是Java](http://dirtsimple.org/2004/12/python-is-not-java.html) – Tadeck

+5

+1 @Tadeck非常重要的事情“Python不是java的” – BlaShadow

2

我不会以不同于我期望来自其他对象的方法来访问它们的方式来访问所述对象的方法中的对象的属性。为什么?我不确定,这似乎很奇怪。

如果您使用properties decorator,Python使得这非常简单,因为它不需要名为“get_foo”/“set_foo”的getter/setter。