3

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
  • Use the property if you are going to have a property. But I wouldn't have a property to begin with in this case. Just a normal attribute Commented Oct 26, 2018 at 15:06
  • Why create a property an not use it? The overhead for normal business applications is 100% neglectable. If you call the property every microsecond we could start talking about performance. If you create a property then you do not want to access the raw value. This prevents you from getting the benefits of a property. That is decoupling of the internal data representation of your class. Commented Oct 26, 2018 at 15:25

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't the __get__() overhead be negligible anyhow? I don't imagine the overhead is worth the headache possibly introduced by referencing a pre-processed private attribute when you actually need the post.
@Idlehands The overhead is negligible until you write it to do something complex. In principle there could be anything in there.
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.