Python

객체지향 프로그래밍 복습

해파리냉채무침 2024. 4. 5. 19:06

출처: 차근차근 실습하며 배우는 파이토치 딥러닝 프로그래밍

 

클래스는 , 인스턴스는 이 틀로부터 생성된 개별적인 실체다.

클래스는 속성이라고 하는 클래스 안의 변수(파라미터)를 가지고, 함수(def)로 정의되는 것은 메서드라고 한다. 

 

Point

import matplotlib.pyplot as plt
import matplotlib.patches as patches
class Point:
  def __init__(self,x,y):
    self.x = x
    self.y = y
  def draw(self):
    plt.plot(self.x,self.y,marker='o',markersize=10,c='k')

__init__은 초기화 처리를 위한 함수, self는 인스턴스 자신이다. 

p1 = Point(2,3)
p2 = Point(-1,-2)
print(p1.x,p1.y)
print(p2.x,p2.y)

Point 클래스로 인스턴스 변수 p1과 p2를 생성한다.

p1.draw()
p2.draw()
plt.xlim(-4,4)
plt.ylim(-4,4)
plt.show()

draw 함수를 통해 두개의 점을 출력한다.

Circle1

class Circle1(Point):
  def __init__(self,x,y,r):
    super().__init__(x,y)
    self.r= r

위에서 만든 Point 클래스를 상속받아 자식클래스 Circle1을 만들었다. super().__init__(x,y)는 부모클래스 Point의 x,y를 사용한다. 속성 r만이 자식클래스 Circle1이 가지는 속성이다. 

ax = plt.subplot()
p1.draw()
p2.draw()
c1_1.draw()
plt.xlim(-4, 4)
plt.ylim(-4, 4)
plt.show()

여기서 실행된 draw 함수는 Point 클래스로 정의된 draw 함수를 불러왔다. 

Circle2

class Circle2(Point):
  def __init__(self,x,y,r):
    super().__init__(x,y)
    self.r= r
  def draw(self):
    c= patches.Circle(xy=(self.x, self.y), radius=self.r, fc='b', ec='k')
    ax.add_patch(c)

Circle2는 draw 함수가 추가되었다. Point 클래스의 draw함수가 호출되지 않고 내부의 draw 함수만이 호출됐다.

부모 클래스와 같은 이름의 함수를 자식 클래스에서 역할을 달리 정의하는 것을 오버라이드 라고한다.

Circle3

부모클래스(Point) 클래스의 draw 함수를 호출하여 원에 점을 찍고 싶으면 다음과 같이 구현한다.

class Circle3(Point):
  def __init__(self,x,y,r):
    super().__init__(x,y)
    self.r= r

  def draw(self):
    super().draw()

    c = patches.Circle(xy=(self.x, self.y), radius=self.r, fc='b', ec='k')
    ax.add_patch(c)

super().draw()는 부모클래스의 draw 함수를 호출한다.

c3_1 = Circle3(1, 0, 2)
ax = plt.subplot()
p1.draw()
p2.draw()
c3_1.draw()
plt.xlim(-4, 4)
plt.ylim(-4, 4)
plt.show()

클래스에서 생성한 인스턴스를 호출 가능한 함수로 만들때 __call__ 함수를 사용한다.

h는 함수처럼 작동하여 다음과 같이 출력한다. 

class H:
    def __call__(self, x):
        return 2*x**2 + 2
import numpy as np
x = np.arange(-2, 2.1, 0.25)
print(x)
h = H() 
y = h(x)
print(y)

[-2. -1.75 -1.5 -1.25 -1. -0.75 -0.5 -0.25 0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]

[10. 8.125 6.5 5.125 4. 3.125 2.5 2.125 2. 2.125 2.5 3.125 4. 5.125 6.5 8.125 10. ]