본문 바로가기
Python

[OOP] Example: MObject, Point, and Class

by ds31x 2024. 3. 23.

그려지는 객체를 추상화한 MObject 를 super-class로 하고,

"점"을 추상화한 Point 클래스와

Point 클래스를 상속하여

"원"을 추상화한 Circle 클래스를 간단히 만들어 봄.

 

사실 Circle 클래스는 Point 클래스와 is-a 관계 보다는 has-a 관계가 어울리지만,

연습을 위해서 만들어 봄.


Environment

matplotlib를 사용하여 그릭기 때문에 해당 라이브러리는 설치되어야 함.
(Test 된 환경은 Python 3.12.1과 matplotlib 3.8.3임.)


Files

src 파일들의 구성은 다음과 같음.

oop_test.py
oop
├── Circle.py
├── MObject.py
└── Point.py

oop_test.py

test를 위한 main script.

import matplotlib.pyplot as plt
import matplotlib
import oop.Circle
import oop.Point

def test_external_axes():
    fig,axes = plt.subplots(figsize=(10,10))
    a = oop.Point.Point(2,2,axes)
    axes = a.draw()
    b = oop.Circle.Circle(4,4,2,axes)
    b.draw()
    plt.show()

def test_internal_axes():
    a = oop.Point.Point(2,2)
    axes = a.draw()
    b = oop.Circle.Circle(4,4,2,axes)
    b.draw()
    b.show()

if __name__ == "__main__":
    print(matplotlib.__version__)
    # test_external_axes()
    test_internal_axes()

MObject.py

import matplotlib.pyplot as plt

class MObject:

    def __init__(self,_axes=None):
        self.figure = None
        self.axes = None
        if self.axes == None:
            if _axes == None:
                self.figure, self.axes = plt.subplots(
                    figsize=(5,5)
                )
                # self.fig = plt.figure(
                #     figsize=(5,5),
                #     facecolor = 'w',
                # )
                # self.axes = self.fig.add_axes(
                #     (0.1,0.1,0.8,0.8),
                # )
            else:
                self.axes = _axes
        else:
            if _axes == None:
                pass
            else:
                self.axes = _axes

    def draw(self):
        pass # to be implemented

    def __call__(self):
        return self.draw()

    def show(self):
        plt.show()

Point.py

import matplotlib.pyplot as plt
from .MObject import MObject

class Point(MObject):

    def __init__(self, x, y, _axes=None):
        super().__init__(_axes)
        self.x = x
        self.y = y
        if _axes != None:
            self.axes = _axes

    def draw(self):
        self.axes.plot(self.x, self.y, marker='o', c='r')
        return self.axes


if __name__ == "__main__":
    a = Point(3,3)
    a.draw()
    a.show()

Circle.py

import matplotlib.pyplot as plt
import matplotlib.patches
from .Point import Point

class Circle(Point):

    def __init__(self, x, y, r, _axes=None):
        super().__init__(x,y,_axes)
        self.r = r

    def draw(self):
        super().draw()
        c = matplotlib.patches.Circle(
            xy = (self.x,self.y),
            radius= self.r,
            fc = 'b',
            ec = 'k', 
        )
        self.axes.add_patch(c)
        return self.axes

if __name__ == "__main__":
    a = Circle(3,3,1)
    a.draw()
    a.show()

https://dsaint31.me/mkdocs_site/python/oop/oop_1_04_relationship/

 

BME228

OOP : Is-a and Has-a Relationship OOP에서 설계 단계 중 가장 중요한 부분 중 하나가 object간의 관계를 정하는 것이다. 사용할 수 있는 관계들 중 가장 유명한 것은 다음과 같은 2가지 이다. is-a relationship ha

dsaint31.me

2024.03.18 - [Python/matplotlib] - [matplotlib] patches: 도형 그리기.

 

[matplotlib] patches: 도형 그리기.

patches 는 모듈은 Artist 의 subclass인 Patch 클래스들을 제공하여, 다음의 다양한 2D 도형을 쉽게 그릴 수 있게 해줌. Arc (호), Circle (원), CirclePolygon (원의 근사 다각형), Ellipse (타원), Arrow (화살표), FancyA

ds31x.tistory.com

https://dsaint31.me/mkdocs_site/python/oop/oop_1_03_inheritance/

 

BME228

Inheritance (상속) OOP에서 애용되는 Object간의 관계(relation) 중의 하나이다. Inheritance를 통해 생성되는 관계가 is-a관계 (이후 다룸)임. Hierarchy(계층화)와 함께 modularity (모듈화)와 코드의 재사용성을

dsaint31.me

 

728x90

'Python' 카테고리의 다른 글

[DL] Tensor에서 maximum, minimum 찾기  (0) 2024.03.28
[Python] Enum (열거형, Enumeration Type)  (0) 2024.03.24
[DL] PyTorch: Autograd (Basic)  (1) 2024.03.22
[DL] PyTorch: view, data, and detach  (0) 2024.03.22
[DL] PyTorch: TPU사용하기  (0) 2024.03.21