그려지는 객체를 추상화한 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/
2024.03.18 - [Python/matplotlib] - [matplotlib] patches: 도형 그리기.
https://dsaint31.me/mkdocs_site/python/oop/oop_1_03_inheritance/
'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 |