250x250
Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

Python 연습장

함수 return 값이 많을 경우 본문

코딩

함수 return 값이 많을 경우

포숑 2022. 2. 15. 06:51
728x90

이런 함수가 있다고 가정해보자

def func(x,y) :

    a = x+y
    b = x-y
    c = x*y
    d = x/y
    e = x**y
    f = x//y
    
    return a,b,c,d,e,f

 

이 함수는 무려 return 값이 6개다. return 값을 받으려면 6개 변수를 일일히 입력해줘야 한다.

r1, r2, r3, r4, r5, r6 = func(3,1)

 

좀 더 심플하게 여러 변수를 받고 필요할때만 불러내서 사용할 수 있는 방법이 있다.

 

첫번째, collections namedtuple 을 활용하면 된다.

from collections import namedtuple

def func(x,y) :

    a = x+y
    b = x-y
    c = x*y
    d = x/y
    e = x**y
    f = x//y
    
    collec = namedtuple('collect', 'a, b, c, d, e, f')
	#혹은 collec = namedtuple('collect', 'a b c d e f')
    
    return collec(a,b,c,d,e,f)

calcul = func(3,1)

print(calcul.a, calcul.b, calcul.c)

 

좀 더 직관적으로 a 를 plus 로, b 를 minus .. 등등으로 변환해서 받으면 사용하기 편해진다.

 

from collections import namedtuple

def func(x,y) :

    plus = x+y
    minus = x-y
    multiple = x*y
    div = x/y
    power = x**y
    floor_div = x//y
    
    collec = namedtuple('collect', 'plus, minus, multiple, div, power, floor_div')
    
    return collec(plus, minus, multiple, div, power, floor_div)

calcul = func(3,1)

print(calcul.plus, calcul.minus, calcul.div)

 

 

두번째 방법은 class 를 사용하는 것이다.

 

class 를 활용하는 방법도 여러가지다. 

먼저 아래처럼 클래스 안에 각 함수들을 넣고 함수처럼 사용하기. named tuple 사용하는 것보다는 조금 더 깔끔해보인다.

class cal :
    def plus(x,y):
        return x + y
    def minus(x,y):
        return x - y
    def mulitple(x,y):
        return x * y
    def div(x,y):
        return x/y
    def power(x,y):
        return x**y
    
print(cal.plus(3,1)) # 4

 

다음 self 로 x,y 값 입력받아서 class 를 호출하고, 호출된 class 에서 함수 불러와서 계산하기.

물론 이런 예시처럼 수식이 간단한 경우는 별로 유용하지 않다. 괜히 self.만 붙어서 지저분해질 뿐이다. 

class cal :
    def __init__(self,x,y):
        self.x = x 
        self.y = y
    def plus(self):
        return self.x + self.y
    def minus(self):
        return self.x - self.y
    def mulitple(self):
        return self.x * self.y
    def div(x,y):
        return self.x/self.y
    def power(x,y):
        return self.x**self.y

calcul = cal(3,1) # class 호출 시 init 함수에 들어가는 x,y 값 지정
print( calcul.plus() ) #4

 

또 다음은 class 를 그냥 지정해놓고 값 넣어주기. 이거는 연산한 값을 저장해놓고 불러올 때 사용하는 거지 함수처럼 쓰이는 건 아니다.

나중에 불러오기 좋게 variable 을 class 내에 모아준다고 보면 될것 같다. 

 

x= 3
y= 1

class cal :
    None

cal.plus = x+y
print(cal.plus) # 4 

cal.minus = x-y
print(cal.minus) # 2

cal.multiple = x*y
print(cal.multiple) # 3


####


a= 2
b= 2 

class cal2 :
    None
   
cal2.plus = a+b
cal2.minus = a-b
cal2.multiple = a*b

 

처음에 이 같은 상황에서 무조건 class 만 쓰려고 했는데 namedtuple 사용하는게 더 효율적인 경우도 있었다.

다 알아두고 상황에 맞게 써야겠다.

 

 

728x90
Comments