Which is better practice; manipulating properties with accessors by @property
or self.property
?
The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.
A data property has a value, which may or may not be writable, whereas an accessor property has a getter-setter pair of functions to set and retrieve the property value. The attributes of a data property are value , writable , enumerable , and configurable .
The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.
Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
If you are just using straight accessors, then stick to @property
(unless you come from Python and are turned off by the @
sigil hehe) otherwise:
It's entirely up to you. But self.property
can be useful in some circumstances where you need to ensure the property is initially set up:
def property
@property ||= []
end
# don't need to check if @property is `nil` first
self.property << "hello"
Also beware that there is a slight overhead to using self.property
over @property
as self.property
is a method call.
NOTE: The reason i'm using self.property
over just property
is because the corresponding setter method property=
requires an explicit receiver: self.property=
, so I choose to use the explicit receiver with both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With