Numpy. section1 : 객체와 ndarray. Lec2. 스페셜 메소드

timekeeep·2023년 2월 9일

Numpy

목록 보기
1/28

[1] special methods of int objects

  • object는 data와 method를 가지고 있음
  • special methods는 컴퓨터가 쓰려고 만든 method
#  [1] special methods of int objects

a, b = 10 , 20

for attr in zip(dir(a), dir(b)):
    print(attr)

#새로운 오브젝트를 연산을 통해 생성 

c = a + b


#special method로 바꿔줌

#(1) 
print(a+b)
print(a.__add__(b))

#(2)

a = [1,2,3]

print(len(a))
print(a.__len__())

print(a-b, a.__sub__(b))
print(a * b, a.__mul__(b))
print(a**b, a__pow__(b))
print(a/b, a.__truediv__(b))
print(a//b, a.__floordiv__(b))
print(a % b, a.__mod__(b))

#special methods의 유용성

a,b,c,d,e = 1.2 ,3.5, 4.2, 4.2, 4.5

result = (a+b)**c - (d/e)
result = ((a.__add__(b)).__pow__(c)).__sub__(d.truediv__(e))

[2] Different special methods in different objects

  • 같은 special method라도 object type에 따라서 다르게 동작한다
  • ndarray에서의 __add__함수는 vector의 element wise 할때 이용된다
# [2] Different special methods in different objects

a,b = 10, 20
print(a + b, a * b)

list1, list2 = [1,2,3] , [4,5,6]

print(list1 + list2) #[1,2,3,4,5,6]
print(3*list) #[1,2,3,1,2,3,1,2,3]


# ndarray의 __add__연산 -> vector 행렬 연산 (element wise)

import numpy as np

a_list = [1,2,3]
b_list = [4,5,6]

print("__add__ of lists: ", a_list.__add__(b_list)) # __add__ of lists: [1,2,3,4,5,6]

a_np = np.array(a_list)
b_np = np.array(b_list)

print("__add__ of ndarrays: ", a_np.__add__(b_np)) # __add__ of ndarrays: [5,7,9]
profile
Those who are wise will shine like the brightness of the heavens, and those who lead many to righteousness, like the stars for ever and ever

0개의 댓글