class Singer: # 클래스
def sing(self): # 메서드
return "Lalala~"
taeji = Singer() # 인스턴스
taeji.sing() # 객체의 메서드
>>> 'Lalala~'
상위 클래스에서 정의된 변수와 메서드를 하위 클래스에서 재 정의
# 부모 클래스 Animal
class Animal:
height = 30
def get_height(self):
print(f"Animal {self.height}")
# 자식 클래스 Dog
class Dog(Animal):
height = 20
def get_height(self):
print(f"Dog {self.height}")
# 자식 클래스 Cat
class Cat(Animal):
height = 20
def get_height(self):
print(f"Parent {super().height}")
# Dog 클래스 인스턴스 생성
dog = Dog()
dog.get_height() # Dog 20
# Cat 클래스 인스턴스 생성
cat = Cat()
cat.get_height() # Parent 30
함수나 메서드의 기능을 간단하게 수정하거나 확장
# 데코레이터 생성
@ 데코레이터
def 함수이름():
코드
def trace(func): # 호출할 함수를 매개변수로 받음
def wrapper():
print(func.__name__, '함수 시작') # __name__으로 함수 이름 출력
func() # 매개변수로 받은 함수를 호출
print(func.__name__, '함수 끝')
return wrapper # wrapper 함수 반환
@trace
def hello():
print('hello')
@trace
def world():
print('world')
hello() # 함수를 그대로 호출
world() # 함수를 그대로 호출
>>> hello 함수 시작
>>> hello
>>> hello 함수 끝
>>> world 함수 시작
>>> world
>>> world 함수 끝