23

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 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())
hatmatrix
  • 42,883
  • 45
  • 137
  • 231
  • 4
    Check for the `property` built-in function: http://docs.python.org/library/functions.html#property – eumiro Nov 28 '11 at 15:03
  • 3
    I don't know where you've read this, but I'll bet it wasn't in any Python context. In Python, the opposite is true. – Daniel Roseman Nov 28 '11 at 15:11

2 Answers2

48

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.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 19
    +1 Additional reason for doing that: [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html) – Tadeck Nov 28 '11 at 15:11
2

I wouldn't access attributes of an object in methods of said object by a different way than what I would expect methods from other objects to access them. Why? I'm not sure, it just seems very weird.

Python makes this really easy if you use the properties decorator which eliminates the need for getters/setters named like "get_foo" / "set_foo".

Wieland
  • 1,663
  • 14
  • 23