23
votes

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())
2
Check for the property built-in function: docs.python.org/library/functions.html#property - eumiro
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

2 Answers

48
votes

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.

2
votes

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".