언더스코어
더블언더스코어
class Klass:
def __init__(self, x):
self.__x = x
kls = Klass(10)
kls._Klass__x
# 속성을 이용한 정렬에 사용할 수 있는 표준 라이브러리 임포트
from operator import attrgetter
class Page:
book_title = "Python book"
def __init__(self, num, content, section=None):
self.num = num
self.content = content
self.section = section
def output(self):
return f"{self.content}"
# 클래스 메서드의 첫 번째 인수는 클래스 객체
@classmethod
def print_pages(cls, *pages):
# 클래스 객체 이용
print(cls.book_title)
# 정렬출력
for page in sorted(pages, key=attrgetter('num')):
print(page.output())
first = Page(1, "first page")
second = Page(2, 'second page')
third = Page(3, 'third page')
Page.print_pages(first, third, second)
Python book #출력값
first page
second page
third page
first.print_pages(first, third, second)
Python book #출력값
first page
second page
third page
class Page:
def __init__(self, num, content, section=None):
self.num = num
self.content = content
self.section = section
@staticmethod
def check_blank(page):
return bool(page.content)
클래스에서 상속이란, 물려주는 클래스(Parent Class, Super class)의 내용(속성과 메소드)을 물려받는 클래스(Child class, sub class)가 가지게 되는 것
- 베이스 클래스(부모)의 속성을 상속 받는 개념
- 오버라이드 : 부모 클래스가 가진 메서드와 같은 이름의 메서드를 다시 정의
- super() : 부모의 클래스의 메서드를 호출
class Page:
def __init__(self, num, content):
self.num = num
self.content = content
def output(self):
return f'{self.content}'
class TitlePage(Page):
def output(self):
title = super().output()
return title.upper()
title = TitlePage(0, 'Python book')
title.output()
'PYTHON BOOK' #출력값
class HTMLPageMixin:
def to_html(self):
return f'<html>{self.output()}<html>'
class WebPage(Page, HTMLPageMixin):
pass
page = WebPage(0, 'web content')
page.to_html()
'<html>web content<html>' #출력값