길/Python

Class Methods / Static Methods / Properties

7he8oy 2021. 2. 13. 08:47

Methods는 기본적으로 클래스의 인스턴스에 의해 작동하지만(클래스는 self 인자로 전달됩니다)

 

Class Methods는 클래스에 의해 작동한다. 

 

아래 예시는 class method를 사용하여,

클래스와 다른 파라미터를 이용해서 인스턴스를 생성하는 것을 보여준다.

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def calculate_area(self):
        return self.width * self.height


 # class method decorator
 # 첫번째 인자는 class가 들어온다.(cls)
    @classmethod     				
    def new_square(cls, side_length):
        return cls(side_length, side_length)
       

square = Rectangle.new_square(5)
print(square.calculate_area())

Static Methods는 class 안에 있는 보통의 함수와 똑같다.

class Pizza:
    def __init__(self, toppings):
        self.toppings = toppings

    def __repr__(self):
        return 'Pizza({})'.format(self.toppings)

    @staticmethod
    def validate_topping(topping):
        if topping == "pineapple":
            raise ValueError("No pineapples!")
        else:
            return True

ingredients = ["cheese", "onions", "spam"]
if all(Pizza.validate_topping(i) for i in ingredients):
    pizza = Pizza(ingredients)
    print(pizza)
    
#Pizza(['cheese', 'onions', 'spam'])

 

Properties

setter/getter 함수를 정의하는 것으로 property를 부여할 수 있다.

 

setter function은 속성의 값을 정하고 

getter function은 그 값을 가져온다.

class Pizza:
    def __init__(self, toppings):
        self.toppings = toppings

    @property
    def pineapple_allowed(self):
        return False

pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
class Pizza:
    def __init__(self, toppings):
        self.toppings = toppings
        self._pineapple_allowed = False

    @property
    def pineapple_allowed(self):
        return self._pineapple_allowed

    @pineapple_allowed.setter
    def pineapple_allowed(self, value):
        if value:
            password = input("Enter the password: ")
            if password == "Sw0rdf1sh!":
                self._pineapple_allowed = value
            else:
                raise ValueError("Alert! Intruder!")

pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)

 

' > Python' 카테고리의 다른 글

str.isdigit()  (0) 2021.02.13
Class Properties  (0) 2021.02.13
Data Hiding  (0) 2021.02.12
Object Lifecycle / reference count  (0) 2021.02.12
클래스 / 객체 / 인스턴스 구분  (0) 2021.02.12