1.기본
class Test: __name = "John" def get_name(self): return self.__name def set_name(self, value): self.__name = value if __name__ == "__main__": t = Test() print(t.get_name()) t.set_name("David") print(t.get_name())
2. property 사용
class Test: __name = "John" def get_name(self): return self.__name def set_name(self, value): self.__name = value name = property(get_name, set_name) if __name__ == "__main__": t = Test() print(t.name) t.name = "David" print(t.name)
3. @property(데코레이터:Decorator) 사용
class Test: __name = "John" @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value if __name__ == "__main__": t = Test() print(t.name) t.name = "David" print(t.name)
4. 여러 속성에 대해서 동일하게 처리해야할 경우, @property를 사용하면 코드가 지저분해지므로, Descriptor를 하면 코드가 깔끔하게 정리됨.
class T: __name = "" def __get__(self, instance, owner): return getattr(instance, "__name") def __set__(self, instance, value): setattr(instance, "__name", value) class Test: name = T() if __name__ == "__main__": t = Test() t1 = Test() t2 = Test() t.name = "David" t1.age = 40 t2.address = "Korea" print(t.name, t1.age, t2.address)