So I've read that you're supposed to access object attributes through getter/setter methods like object.get_this()
or object.set_that(value)
. Does this code hold for methods that are also defined within the class? Or they are only meant to be used with object instances. For instance, is it idiomatic to do it this way,
class test: def __init__(self,value): self.value = value def get_value(self): return self.value def method(self): return some_operation(self.value)
with get_value()
defined for accessing value
for an object instance, or should get_value()
also be used within class methods?
class test: def __init__(self,value): self.value = value def get_value(self): return self.value def method(self): return some_operation(self.get_value())
To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .
The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use.
In python do not use getter/setter methods. Instead just access the attribute itself, or, if you need code to be run every time the attribute is accessed or set, use properties.
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