Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Object Oriented Programming/Getters and Setters

From Wikibooks, open books for an open world
<Object Oriented Programming
This page or section is an undeveloped draft or outline.
You can help todevelop the work, or you can ask for assistance in theproject room.

Getters and Setters (also known as accessor and mutator methods respectively) are two types of methods used to control the access and modification of class attributes (also called properties or member variables).

Getter

[edit |edit source]

A getter method is used toretrieve the value of a private or protected class attribute. It provides read-only access to the attribute, allowing other parts of the program to retrieve its value without directly accessing the attribute. By using a getter, you can control how the attribute is accessed and apply any necessary logic or validation before returning the value.


In most programming languages, the naming convention for a getter method is to prefix it with "get," followed by the attribute name. For example, if you have a private attribute age, the corresponding getter method would typically be namedgetAge().

classPerson:   def__init__(self,name,age):       self._name=name       self._age=age   defgetAge(self):       returnself._age# Usageperson=Person("John Doe",25)print(person.getAge()) # Output: 25

Setter

[edit |edit source]

A setter method is used tomodify the value of a private or protected class attribute. It provides a way to update the attribute while enforcing any necessary constraints or validation rules before making the change. By using a setter, you can control how the attribute is modified and prevent any inappropriate changes.

In most programming languages, the naming convention for a setter method is to prefix it with the word "set," followed by the attribute name. For example, if you have a private attribute age, the corresponding setter method would typically be namedsetAge().

classPerson:def__init__(self,name,age):self._name=nameself._age=agedefsetAge(self,new_age):ifnew_age>=0:self._age=new_age# Usageperson=Person("John",25)person.setAge(30)print(person.getAge())# Output: 30person.setAge(-5)# The age will not be updated because of the validation in the setter methodprint(person.getAge())# Output: 30 (age remains unchanged)

See also

[edit |edit source]
Lifetime Management
Static vs Dynamic
Retrieved from "https://en.wikibooks.org/w/index.php?title=Object_Oriented_Programming/Getters_and_Setters&oldid=4312624"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp