흰 스타렉스에서 내가 내리지

[Python] @Property 본문

Python

[Python] @Property

주씨. 2022. 1. 1. 16:55
728x90
# 1
class User1:
    def __init__(self, name, age):
        self.name = name
        self.age = self.set_age(age) ##
    
    def get_age(self):
        return self._age
    
    def set_age(self, age):
        if age < 0:
            raise ValueError("Invalid age")
        self._age = age

        
# 2
class User2:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def get_age(self):
        return self._age
    
    def set_age(self, age):
        if age < 0:
            raise ValueError("Invalid age")
        self._age = age
    
    age = property(get_age, set_age)    ##


# 3
class User3:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @property
    def age(self):
        return self._age
    
    @age.setter    # [필드명].setter
    def age(self, age):
        if age < 0:
            raise ValueError("Invalid age")
        self._age = age
        
    @property
    def msg(self):
        return "message"
        

user3 = User3("joo", 25)
print(user3.name)
print(user3.age)
user3.age = 4
print(user3.age)
print(user3.msg)

# joo
# 25
# 4
# message

# 1 : 기존의 getter, setter 함수

# 2 : property() 함수

# 3: @property 데코레이터

 

@property를 활용한 코드 링크 : 여기