파이썬+operator+이해하기 20160409
TRANSCRIPT
PYTHON OPERATOR
VERSION 2.X
Moon Yong Joon
연산자 구조
연산자와 special method파이썬 문법의 연산자는 각 type class 내부에 대응하믄 special method 가 존재
연산자 SpecialMethod
각 타입별로 연산자는 special method 와 매칭
연산자 우선순위순위 구분 Operator Description
0 그룹 ( ) Parentheses (grouping)
1 함수 f(args...) Function call
2 참조 x[index:index] Slicing
3 참조 x[index] Subscription
4 참조 x.attribute Attribute reference
5 산술 ** Exponentiation( 제곱 )
6 비트 ~x Bitwise not
7 부호 +x, -x Positive, negative
8 산술 *, /, % Multiplication, division, remainder
9 산술 +, - Addition, subtraction
10 비트 <<, >> Bitwise shifts
11 비트 & Bitwise AND
12 비트 ^ Bitwise XOR
13 비트 | Bitwise OR
14 비트 in, not in, is, is not, <, <=, >, >=,<>, !=, == Comparisons, membership, identity
15 논리 not x Boolean NOT
16 논리 and Boolean AND
17 논리 or Boolean OR
18 함수 lambda Lambda expression
부호변환
부호연산숫자 객체에 대한 부호 변환하는 연산
Operation Syntax Function Method
Negation (Arithmetic) - a neg(a)x.__neg__()
Positive + a pos(a) x.__pos__()
부호변환 예시숫자 타입의 부호를 변환
import operator as op
i = 10print(" negative : ", -(10))print(" neg(a) : ", op.neg((10)))print("a.__neg__ : ", (10).__neg__())print(" positive : ", -(-10), +(10))print(" pos(a) : ", op.pos((10)))print("a.__pos__ : ", (10).__pos__())
(' negative : ', -10)(' neg(a) : ', -10)('a.__neg__ : ', -10)(' positive : ', 10, 10)(' pos(a) : ', 10)('a.__pos__ : ', 10)
산술 연산
산술연산 : 정방향숫자 객체들에 대한 수학적인 산술연산
Operation Syntax Function Methodaddition x + y add(a, b) x.__add__(y)
subtraction x - y sub(a, b) x.__sub__(y)
multiplication x * y mul(a, b) x.__mul__(y)
division x / y div(a, b) x.__div__(y)
division x / y truediv(a, b) x.__truediv__(y)
floor division x // y floordiv(a, b) x.__floordiv__(y)
modulo (remainder) x % y mod(a, b) x.__mod__(y)
floor division & modulo divmod(x, y) N/A x.__divmod__(y)
raise to power x ** y pow(a, b) x.__pow__(y)
산술연산 예시 : operator 모듈Operator 모듈을 import 해서 사용
import operator as op
i = 10print(" operator module ")print(" add : ",op.add(i,1))print(" sub : ",op.sub(i,1))print(" mul : ",op.mul(i,10))print(" div : ",op.div(i,10))print(" div : ",op.floordiv(i,3))print(" true div : ", op.truediv(i,3))print(" mod div : ",op.mod(i,3))print(" divmod : ", "N/A")print(" power : ",op.pow(i,3))
operator module (' add : ', 11)(' sub : ', 9)(' mul : ', 100)(' div : ', 1)(' div : ', 3)(' true div : ', 3.3333333333333335)(' mod div : ', 1)(' divmod : ', 'N/A')(' power : ', 1000)
산술연산 예시 : int methodInt class 내의 special method 이용해 계산
i = 10print(" special method ")print(" add : ",i.__add__(1))print(" sub : ",i.__sub__(1))print(" mul : ",i.__mul__(10))print(" div : ",i.__div__(10))print(" floor div : ",i.__floordiv__(3))print(" true div : ", i.__truediv__(3))print(" mod div : ",i.__mod__(3))print(" divmod : ", i.__divmod__(3))print(" power : ", i.__pow__(3))
special method (' add : ', 11)(' sub : ', 9)(' mul : ', 100)(' div : ', 1)(' floor div : ', 3)(' true div : ', 3.3333333333333335)(' mod div : ', 1)(' divmod : ', (3, 1))(' power : ', 1000)
산술연산 예시 : 연산자파이썬 문법의 연산자 이용
i = 10print(" operator ")print(" add : ",i + 1)print(" sub : ",i - 1)print(" mul : ",i * 10)print(" div : ",i / 10)print(" floor div : ",i // 3)print(" true div : ", i / 3.0)print(" mod div : ",i % 3)print(" divmod : ", divmod(i, 3))print(" power : ", i ** 3 )
operator (' add : ', 11)(' sub : ', 9)(' mul : ', 100)(' div : ', 1)(' floor div : ', 3)(' true div : ', 3.3333333333333335)(' mod div : ', 1)(' divmod : ', (3, 1))(' power : ', 1000)
산술연산 : 역방향수학적인 산출연산에 대한 역방향 메소드 제공 계산결과는 정방향과 동일
Operation Syntax Function Methodaddition x + y add(a, b) y.__radd__(x)
subtraction x - y sub(a, b) y.__rsub__(x)
multiplication x * y mul(a, b) y.__rmul__(x)
division x / y div(a, b) y.__rdiv__(x)
division x / y truediv(a, b) y.__rtruediv__(x)
floor division x // y floordiv(a, b) y.__rfloordiv__(x)
modulo (remainder) x % y mod(a, b) y.__rmod__(x)
floor division & modulo divmod(x, y) N/A y.__rdivmod__(x)
raise to power x ** y pow(a, b) y.__rpow__(x)
산술연산 역방향 예시사칙연산이 정방향이나 역방향이나 계산은 동일
print(" right hand operator ")print(" x + y ", (8).__radd__(2))print(" x + y ", (2).__add__(8))
print(" x ** y ", (3).__rpow__(2))print(" x ** y ", (2).__pow__(3))
right hand operator (' x + y ', 10)(' x + y ', 10)(' x ** y ', 8)(' x ** y ', 8)
비트 연산
비트연산 설명비트연산에 대해서는 실제 숫자의 비트를 가지고 연산
Operation Syntax 설명left bit-shift x << y y 만큼 왼쪽으로 bit 이동 : 산식은 (x * (2** y) )
right bit-shift x >> y y 만큼 오른쪽으로 bit 이동 : 산식은 (x // (2** y) )
bitwise and x & y x 와 y 이 동일한 비트값만 (1 또는 0) 남고 동일하지 않으면 0 처리bitwise xor x ^ y x 와 y 에서 서로 대응되지 않는 값만 남김 bitwise or x | y x 와 y 에서 1 이 있는 값은 1 로 처리 0 이 동일한 경우 0 처리
Bitwise Inversion ~ a a 의 비트를 반대로 표시
비트연산파이썬 연산자 ,operator 모듈내의 함수와 int 메소드간의 관계
Operation Syntax Function Methodleft bit-shift x << y lshift(a, b) x.__lshift__(y)
right bit-shift x >> y rshift(a, b) x.__rshift__(y)
bitwise and x & y and_(a, b) x.__and__(y)
bitwise xor x ^ y xor(a, b) x.__xor__(y)
bitwise or x | y or_(a, b) x.__or__(y)
Bitwise Inversion ~ a invert(a) x.__invert__()
비트 연산 예시비트연산Import operator
print(" lshift x * (2**y) ")print(" << : ", 10 << 2)print(" lshift : ", op.lshift(10,2))print(" __lshift__ : ", (10).__lshift__(2))print(" rshift x // (2**y) ")print(" >> : ", 10 >> 2)print(" rshift : ", op.rshift(10,2))print(" __rshift__ : ", (10).__rshift__(2))print(" bit and ", oct(10), oct(2))print(" & : ", 10 & 2)print(" and_(a, b) : ", op.and_(10,2))print("x.__and__(y) : ", (10).__and__(2))print(" bit or ", oct(10), oct(4))print(" | : ", 10 | 4)print(" or_(a, b) : ", op.or_(10,4))print("x.__or__(y) : ", (10).__or__(4))print(" bit xor ", oct(10), oct(6))print(" ^ : ", 10 ^ 6)print(" xor(a, b) : ", op.xor(10,6))print("x.__xor__(y) : ", (10).__xor__(6))print(" bit inversion ", oct(10))print(" ~ : ", ~(10) )print(" invert(a) : ", op.invert(10))print("x.__invert__(y) : ", (10).__invert__())
lshift x * (2**y) (' << : ', 40)(' lshift : ', 40)(' __lshift__ : ', 40) rshift x // (2**y) (' >> : ', 2)(' rshift : ', 2)(' __rshift__ : ', 2)(' bit and ', '012', '02')(' & : ', 2)(' and_(a, b) : ', 2)('x.__and__(y) : ', 2)(' bit or ', '012', '04')(' | : ', 14)(' or_(a, b) : ', 14)('x.__or__(y) : ', 14)(' bit xor ', '012', '06')(' ^ : ', 12)(' xor(a, b) : ', 12)('x.__xor__(y) : ', 12)(' bit inversion ', '012')(' ~ : ', -11)(' invert(a) : ', -11)('x.__invert__(y) : ', -11)
augmented operator
augmented operator파이썬에서는 할당연산자와 일반연산자를 축약해서 사용
X += Y X = X+ Y
사칙연산 사칙연산
Operation Syntax Function Methodaddition x += y iadd(a, b) x.__iadd__(y)
subtraction x -= y isub(a, b) x.__isub__(y)
multiplication x *= y imul(a, b) x.__imul__(y)
division x /= y idiv(a, b) x.__idiv__(y)
division x /= y itruediv(a, b) x.__itruediv__(y)
floor division x //= y ifloordiv(a, b) x.__ifloordiv__(y)
modulo (remainder) x %= y imod(a, b) x.__imod__(y)
raise to power x **= y ipow(a, b) x.__ipow__(y)
증가비트연산 비트연산과 할당연산을 같이 사용
Operation Syntax Function Method
left bit-shift x <<= y ilshift(a, b) x.__ilshift__(y)
right bit-shift x >>= y irshift(a, b) x.__irshift__(y)
bitwise and x &= y iand_(a, b) x.__iand__(y)
bitwise xor x ^= y ixor(a, b) x.__ixor__(y)
bitwise or x |= y ior_(a, b) x.__ior__(y)
관계연산
관계연산파이썬 내의 객체 간의 순서와 동등 관계를 처리하는 연산자
Operation Syntax Function Method
Ordering a < b lt(a, b)x.__lt__(y)
Ordering a <= b le(a, b)x.__le__(y)
Equality a == b eq(a, b)x.__eq__(y)
Difference a != b ne(a, b)x.__ne__(y)
Ordering a >= b ge(a, b)x.__ge__(y)
Ordering a > b gt(a, b)x.__gt__()
논리연산
논리연산 논리연산은 boolean 값을 비교해서 처리
Operation Syntax Function Method
and Logical AND a and b NA NA
or Logical OR a or b NA NA
Negation (Logical) not a not_(a) NA
논리연산 예시논리연산
x = Truey = Falseprint('x and y is',x and y)print('x or y is',x or y)print('not x is',not x)
('x and y is', False)('x or y is', True)('not x is', False)
시퀀스 연산
시퀀스 연산시퀀스에 대한 처리
Operation Syntax Function Method
Concatenation seq1 + seq2 concat(seq1, seq2) x.__add__(y)
Sequence Repetition seq * i repeat(seq, i) x.__mul__(y)
Identity a is b is_(a, b) NA
Identity a is not b is_not(a, b) NA
시퀀스연산 예시 : +, *시퀀스 타입 ( 리스트 , 문자열 , 튜플 ) 이 가능한 연산
Import operator as op
print(" sequence operator ")print(" + ", "Hello" + "World")print(" concat ", op.concat("Hello", "World"))print(" __add__ ", "Hello".__add__("World"))print(" * ", "Hello" * 3)print(" __mul__ ", "Hello".__mul__(3))print(" repeat ", op.repeat("Hello", 3))
sequence operator (' + ', 'HelloWorld')(' concat ', 'HelloWorld')(' __add__ ', 'HelloWorld')(' * ', 'HelloHelloHello')(' __mul__ ', 'HelloHelloHello')(' repeat ', 'HelloHelloHello')
시퀀스연산 예시 : is, is not시퀀스 타입 ( 리스트 , 문자열 , 튜플 ) 이 가능한 연산
Import operator as op
print(" is ", "abc" is "abc")print(" is_", op.is_("abc","abc"))print(" is not ", "abc" is not "abcd")print(" is_", op.is_not("abc","abcd"))
(' is ', True)(' is_', True)(' is not ', True)(' is_', True)
container 연산
container 연산시퀀스에 대한 contain 처리
Operation Syntax Function Method
Containment Test obj in seq contains(seq, obj) x.__contains__(y)
Containment Test obj not in seq not_(contains(seq, obj)) NA
container 연산시퀀스에 대한 contain 처리
Import operator as op
print(" in ", "a" in "abc")print(" __contains__", "abc".__contains__('a'))print(" contains", op.contains("abc",'a'))
print(" in ", "a" not in "abc")print(" __contains__", not("abc".__contains__('a')))print(" contains", op.not_(op.contains("abc",'a')))
(' in ', True)(' __contains__', True)(' contains', True)(' in ', False)(' __contains__', False)(' contains', False)
슬라이싱 연산
슬라이싱 연산시퀀스나 컨테이너에 대한 내부 값을 처리 하는 연산
Operation Syntax Function Method
Slice Assignment seq[i:j] = valuessetitem(seq, slice(i, j), values
) __ setitem__
setslice(a, b, c, v) __setslice__
Slice Deletion del seq[i:j]delitem(seq, slice(i, j)) __ delitem__
delslice(a, b, c) __delslice__
Slicing seq[i:j]getitem(seq, slice(i, j)) __ getitem__
getslice(a, b, c) __getslice__
Indexed Assignment obj[k] = v setitem(obj, k, v) __ setitem__
Indexed Deletion del obj[k] delitem(obj, k) __ delitem__
Indexing obj[k] getitem(obj, k) __ getitem__
slicing 내부 조회 / 갱신 / 삭제Sequence 타입 에 대한 원소를 조회 , 갱신 , 삭제를 추가하는 메소드 , 갱신과 삭제는 list 타입만 가능
object.__getslice__(self, i, j)
object.__setslice__(self, i, j, sequence
object.__delslice__(self, i, j)
검색
생성 / 변경
삭제
Slice 를 이용한 처리 예시 Sequence 타입에 대한 slicing 처리
Import operator as op
print(" __getslice__ :", [0,1,2,3].__getslice__(0,2))print(" getslice :", op.getslice([0,1,2,3],0,2))l=[0,1,2,3]print(" __setslice__ :", l.__setslice__(0,2,[99,99]),l)print(" __delslice__ :", l.__delslice__(0,2),l)l=[0,1,2,3]print(" setslice :", op.setslice(l,0,2,[99,99]),l)print(" delslice :", op.delslice(l,0,2),l)
(' __getslice__ :', [0, 1])(' getslice :', [0, 1])(' __setslice__ :', None, [99, 99, 2, 3])(' __delslice__ :', None, [2, 3])(' setslice :', None, [99, 99, 2, 3])(' delslice :', None, [2, 3])
Container 내부 조회 / 갱신 / 삭제List,dict 에 대한 원소를 조회 , 갱신 , 삭제를 추가하는 메소드 , list 는 index 에 범위내에서만 처리됨
object.__getitem__(self, key)
object.__setitem__(self, key, value)
object.__delitem__(self, key)
검색
생성 / 변경
삭제
Item 을 이용한 처리 예시 Sequence 타입에 대한 slicing 처리시 key 부문에 slice() 함수를 이용할 경우 리스트도 처리가 가능Import operator as op
print(" __getitem__ : ", [0,1,2,3].__getitem__(slice(0,2)))print(" getitem : ", op.getitem([0,1,2,3],slice(0,2)))l=[0,1,2,3]print(" __setitem__ :", l.__setitem__(slice(0,2),[99,99]),l)print(" __delitem__ :", l.__delitem__(slice(0,2)),l)l=[0,1,2,3]print(" setitem :", op.setitem(l,slice(0,2),[99,99]),l)print(" delitem :", op.delitem(l,slice(0,2)),l)
(' __getitem__ : ', [0, 1])(' getitem : ', [0, 1])(' __setitem__ :', None, [99, 99, 2, 3])(' __delitem__ :', None, [2, 3])(' setitem :', None, [99, 99, 2, 3])(' delitem :', None, [2, 3])