Should I use property or private attribute?

Viewed 122

Suppose I create a class:

class SomeClass:    
    def __init__(self, some_attribute):
        self._attribute = some_attribute

    @property
    def attribute(self):
        return self._attribute

Then, I add a method new_method to my object that will use the "attribute". Therefore, should I use self._attribute or self.attribute?:

def new_method(self):
    DoSomething(self.attribute) # or     DoSomething(self._attribute)

Does it make any impact or difference?

2 Answers

Using self.attribute will trigger a call to SomeClass.attribute.__get__ and therefore come with more overhead.

Using self._attribute comes with less overhead but will introduce a bug in your code as soon as you add meaningful logic to the definition of attribute.

In my opinion, use self.attribute consistently. If the getter ever becomes a bottleneck, consider caching-strategies before using _attribute and attribute inside the class inconsistently. Sooner or later you will introduce a bug.

My personal opinion is to use self.attribute. The reason is that how it is implemented may change.

Here it is stored as another instance variable, but it could be stored later in an underlying object for whatever reason.

This implementation will of course have a small overhead compared to the direct access.

Related