Kaedah pemutat

Daripada Wikipedia, ensiklopedia bebas.
Lompat ke: pandu arah, cari

Dalam sains komputer, kaedah pemutat (bahasa Inggerisnya mutator method) ialah kaedah yang diguna untuk mengawal perubahan keatas pemboleh ubah. Kaedah pemutat yang digunakan untuk meletakkan nilai kepada pemboleh ubah biasanya dipanggil "setter" manakala yang digunakan untuk mengambil nilai pemboleh ubah dipanggil "getter".

Contoh[sunting | sunting sumber]

Contoh C[sunting | sunting sumber]

Fail student.h

#ifndef STUDENT_H
#define STUDENT_H
 
typedef struct student *student_t;
 
student_t student_new(int age, char *name);
void student_delete(student_t s); 
 
void student_set_age(student_t s, int age);
int student_get_age(student_t s);
 
#endif

Fail student.c

#include "student.h"
 
struct student { int age; char *name; };
 
student_t student_new(int age, char *name) {
  student_t s = malloc(sizeof *s);
  s->age = age; s->name = name;
  return s;
}
 
void student_delete(student_t s) {
  free(s);
}
 
void student_set_age(student_t s, int age) {
  s->age = age;
}
 
int student_get_age(student_t s) {
  return s->age;
}

Fail main.c:

#include "student.h"
 
int main(void) {
  student_t s = student_new(19, "Maurice");
  int old_age = student_get_age(s);
  student_set_age(s, 21);
  student_delete(s);
  return 0;
}

Contoh C++[sunting | sunting sumber]

Fail Student.h:

#ifndef STUDENT_H
#define STUDENT_H
 
#include <string>
 
class Student {
public:
    Student(const std::string& name);
 
    const std::string& name() const;
    void name(const std::string& name);
 
private:
    std::string name_;
};
 
#endif

Fail Student.cpp:

#include "Student.h"
 
Student::Student(const std::string& name) : name_(name) {
}
 
const std::string& Student::name() const {
    return name_;
}
 
void Student::name(const std::string& name) {
    name_ = name;
}

Contoh Python[sunting | sunting sumber]

class Murid:
    def __init__(self, nama):
        self._nama = 0
 
    #Kaedah getter
    @property
    def nama(self):
        return self._nama
 
    #Kaedah setter
    @nama.setter
    def nama(self, nama):
        self._nama = nama
 
ali = Murid("Ali")
print ali.name() #==> Ali
ali.name("Abu")
print ali.name() #==> Abu
ali._name = "Siti" # pintas setter
print ali._name # pintas getter; ==> Siti