Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP: getter/setter methods [duplicate]

Tags:

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()) 
like image 601
hatmatrix Avatar asked Nov 28 '11 14:11

hatmatrix


People also ask

How do you use setters and getters in two different classes?

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 .

What are getter methods and setter methods?

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.

What are the benefits of using getter and setter methods?

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.

What can I use instead of getters and setters?

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.


1 Answers

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.

like image 108
unutbu Avatar answered Nov 26 '22 09:11

unutbu