서로 다른 클래스로 만든 오브젝트끼리의 이벤트를 처리하는 방법.
<방법 1>
class A:
def __init__(self, point):
self.point = point
class B:
def __init__(self, count):
self.count = count
def plus(self, op):
op += self.count
return op
p1 = A(10)
p2 = B(5)
p2.plus(p1.point)
A클래스로 만든 p1의 point와 B클래스로 만든 p2의 count를 B클래스의(p2의) plus 함수로 더하는 처리다.
print(p2.plus(p1.point))
결과는 15.
<방법 2>
class A:
def __init__(self, point):
self.point = point
class B:
def __init__(self, count):
self.count = count
def plus(op1, op2):
op1 += op2
return op1
p1 = A(10)
p2 = B(5)
plus(p1.point, p2.count)
첫 번째 코드에서 plus 함수를 B클래스 밖으로 꺼냈다.
print(plus(p1.point, p2.count))
결과는 그대로 15.
파이썬 - 객체지향의 이해(객체, 클래스)
'프로그래밍 > Python' 카테고리의 다른 글
[Python] numpy(넘파이) 기초 정리 (2) | 2021.03.07 |
---|