Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice - accessing object variables

I've been making a lot of classes an Python recently and I usually just access instance variables like this:

object.variable_name

But often I see that objects from other modules will make wrapper methods to access variables like this:

object.getVariable()

What are the advantages/disadvantages to these different approaches and is there a generally accepted best practice (even if there are exceptions)?

like image 216
jonathan topf Avatar asked Mar 25 '26 16:03

jonathan topf


1 Answers

There should never be any need in Python to use a method call just to get an attribute. The people who have written this are probably ex-Java programmers, where that is idiomatic.

In Python, it's considered proper to access the attribute directly. If it turns out that you need some code to run when accessing the attribute, for instance to calculate it dynamically, you should use the @property decorator.

like image 116
Daniel Roseman Avatar answered Mar 28 '26 07:03

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!