Python공부

Python - 함수(def),딕셔너리 만들기 함수, class

SoSweetStrawberry 2022. 8. 15. 23:45
반응형

-------------------------------------------------<기본 함수>-------------------------------------------------

def add(a,b):
    print('{}+{}={}'.format(a,b,a+b))

add(2,3)
2+3=5

1. 함수에 초기값 넣기 

def add_num(a,b=0):
    c = a-b
    print(f"{a} - {b} = {c}")
    
add_num(5,3)
add_num(b=3,a=5)
add_num(5)
5 - 3 = 2
5 - 3 = 2
5 - 0 = 5

 

2. 매개값 여러개 지정 (튜플 형태로) *

def sum_it3(*arg):  #*arg값을 튜플로 만듬
    print(sum(arg))
    
sum_it3(1,2,3)
6

3. 딕셔너리 만드는 함수  **

def test(**keyargs):   #딕셔너리로 만듬 
    print(type(keyargs))
    print(keyargs.get('name'))
    
test(num=11,name='Smith', dept=10)
test(num=13,dept=20)
<class 'dict'>
Smith
<class 'dict'>
None

 

-------------------------------------------------<기본 클래스>-------------------------------------------------

class Sample:
    def __init__(self,x,y): #변수 초기화
        self.x=x
        self.y=y
       
    def __hash__(self):  #hashCode 설정
        return self.hash(self.x,self.y)
    
    def __eq__(self,other): # == 
        return self.x==other.x and self.y==other.y
    
    def __str__(self): #toString
        return 'x:{}, y:{}'.format(self.x,self.y)

test_1 = Sample(2,3)
test_2 = Sample(2,3)

print(test_1 == test_2)  #__eq__
print(test_1)            #__str__
True
x:2, y:3

 

반응형

'Python공부' 카테고리의 다른 글

Python - Dictionary(딕셔너리)_ get,[ ]의 차이  (0) 2022.08.16
Python - Boolean & if  (0) 2022.08.16
Python - 목록, for문(remove,extend..)  (0) 2022.08.16
Python - for문  (0) 2022.08.15
Python - 기본  (0) 2022.08.15