파이썬 - 게터와 세터 메서드 대신에 일반 속성을 사용하자.

이동욱

2021/06/14

Categories: 파이썬

BATTER WAY 29. 게터와 세터 메서드 대신에, 일반 속성을 사용하자.

class OldResistor(object):
  def __init__(self, ohms):
    self._ohms = ohms

  def get_ohms(self):
    return self._ohms

  def set_ohms(self, ohms):
    self._ohms = ohms


r0 = OldResistor(50e3)
print(f'Before: {r0.get_ohms()}') # Before: 50000.0

r0.set_ohms(10e3)
print(f'Before: {r0.get_ohms()}')')') # After: 10000.0
r0.set_ohms(r0.get_ohms() + 5e3)
class Register(object):
  def __init__(self, ohms):
    self.ohms = ohms
    self.voltage = 0
    self.current = 0


r1 = Register(50e3)
r1.ohms = 10e3

r1.ohms += 5e3
class VoltageResistance(Register):
  def __init__(self, ohms):
    super().__init__(ohms)
    self._voltage = 0

  @property
  def voltage(self):
    return self._voltage

  @voltage.setter
  def voltage(self, voltage):
    self._voltage = voltage
    self.current = self._voltage / self.ohms

r2 = VoltageResistance(1e3)
print(f'Before: {r2.current}') # 0
r2.voltage = 10
print(f'After: {r2.current}')')') # 0.01
class BoundedResistence(Register):
  def __init__(self, ohms):
    super().__init__(ohms)

    @property
    def ohms(self):
      return self._ohms

    @ohms.setter
    def ohms(self, ohms):
      if ohms <= 0:
      raise ValueError(f"{ohms} ohms must be > 0")


r3 = BoundedResistence(1e3)
r3.ohms = 0
class FixedResistence(Register):
  def __init__(self, ohms):
    super().__init__(ohms)

    @property
    def ohms(self):
      return self._ohms

    @ohms.setter
    def ohms(self, ohms):
      if hasattr(self, '_ohms'):
        raise ValueError("Can't set attribute")
        self._ohms = ohms

핵심 정리


참고 문헌

>> Home