I have embedded code in python. I need to access an attribute of an object.
Is doing objectA.attribute_x
faster than objectA.get_attribute_x()
?
From OO point of view, using the getter seems the right thing to do. But which way is computationally cheaper/faster?
Getters and setters are essentially sugar-coated wrappers for methods. So it's going to be slower than directly accessing something.
The class attribute specifies one or more classnames for an element. The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
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.
Return Value: Thus, the name property hides the private instance attribute __name . The name property is accessed directly, but internally it will invoke the getname() or setname() method, as shown below. As you can see above, the getname() method gets called automatically when we access the name property.
Lets find out! It seems like there is more work with the function call, but lets let timeit
have a crack at it:
from timeit import timeit
class Foo():
def __init__(self):
self.bar = "bar"
self.baz = "baz"
def get_baz(self):
return self.baz
print(timeit('foo.bar', setup='import __main__;foo=__main__.Foo()', number=10000000))
print(timeit('foo.get_baz()', setup='import __main__;foo=__main__.Foo()', number=10000000))
On one run on my computer I got:
1.1257502629887313
4.334604475006927
Direct attribute lookup is the clear winner.
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