인스턴스 메소드 (Instance method)
클래스 메소드 (class method)
스태틱 메소드 (static method)
class Rectangle:
count = 0 # 클래스 변수
def __init__(self, width, height):
self.width = width
self.height = height
Rectangle.count += 1
# 인스턴스 메서드
def calcArea(self):
area = self.width * self.height
return area
# 정적 메서드
@staticmethod
def isSquare(rectWidth, rectHeight):
return rectWidth == rectHeight
# 클래스 메서드
@classmethod
def printCount(cls):
print(cls.count)
# 테스트
square = Rectangle.isSquare(5, 5)
print(square) # True
rect1 = Rectangle(5, 5)
rect2 = Rectangle(2, 5)
rect1.printCount() # 2
from abd import *
class StudentBase(metaclass=ABCMeta):
@abstractmethod
def study(self):
pass
def go_to_school(self):
pass
class Student(StudentBase):
def Student()
print('공부하기')
james = Student()
james.study()
# 실행 결과
'''
Traceback (most recent call last):
File "C:\project\class_abc_error.py", line 16, in <module>
james = Student()
TypeError: Can't instantiate abstract class Student with abstract methods go_to_school
'''
# Student 클래스가 go_to_school 메소드를 구현하지 않아 오류 발생
from abc import *
class StudentBase(metaclass=ABCMeta):
@abstractmethod
def study(self):
pass
@abstractmethod
def go_to_school(self):
pass
class Student(StudentBase):
def study(self):
print('공부하기')
def go_to_school(self):
print('학교가기')
james = Student()
james.study()
james.go_to_school()
# 실행 결과
'''
공부하기
학교가기
'''
>>> james = StudentBase()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
james = StudentBase()
TypeError: Can't instantiate abstract class StudentBase with abstract methods go_to_school, study
출처
1. https://zzsza.github.io/development/2020/07/05/python-class/
2. https://dojang.io/mod/page/view.php?id=2389