1.캡슐화: 객체 내부 데이터를 외부에서 직접 접근하지 못하도록 보호
의의:
class ClassName: # <--pascal case
# 생성자(constructor): 인스턴스(객체)가 생성될 때 호출
# 인스턴스 변수를 초기화, 기본 상태 설정
# 하나의 클래스에서 하나만 정의 가능
def __init__(self, name): # __init__(생성자): 객체가 생성될 때 자동 호출되는 초기화 매서드
# 인스턴스 변수
# self: 인스턴스 자기 자신을 가리킴
self.name = name
self.age = 0
# (인스턴스) 메서드
def method_name(self):
print(f"이 인스턴스의 이름은{self.name}입니다.")
pass
# 인스턴스 생성
my_instance = ClassName("I1")
print(my_instance.name)
my_instance.method_name()
another_instance = ClassName("I2")
another_instance.method_name()
# 클래스와 객체
# 클래스: 객체를 만들기 위한 설계도
# 객체: 클래스로부터 만들어진 실제 데이터
# 클래스는 공통적인 속성과 동작을 정의하고, 객체는 이를 기반으로 실제 데이터를 가지는 객체
# 생성자__init __() 함수
# 생성자(Constructor)
# 클래스로부터객체(인스턴스)를 생성할 때 자동으로호출되는초기화함수
# 객체생성시 필요한속성초기화및 기본상태설정에 사용
# __init__()메서드로생성자정의
# 하나의 클래스에 하나의__init__()만 정의가능함
class Book:
def __init__(self, title, author,total_pages, current_page):
self.x1 = title
self.x2 = author
self.x3 = total_pages
self.x4 = current_page
def read_page(self):
if self.x4 > self.x3:
print("책의 범위를 벗어났습니다.")
else:
print(f"현재 {self.x4}페이지를 읽으시고 있는 중입니다.")
pass
# def read_page(self, page):
# self.x4 += page
# if page > self.x3:
# self.x4 = self.x3
# print("책의 범위를 벗어났습니다.")
# else:
# print(f"현재 {page}페이지를 읽으시고 있는 중입니다.")
# pass
def progress(self):
ratio = self.x4 / self.x3 * 100
result = round(ratio, 1) # 소수점 첫 째 자리까지 반올림
print(f"전체 중 {result}(%) 읽으셨습니다.")
Dongyuns_Story = Book("Dongyuns_story", "Dongyun2", 500, 245)
Dongyuns_Story.read_page()
Dongyuns_Story.progress()
결과

class Rectangle:
def __init__(self, width, height):
self.x1 = width
self.x2 = height
def area(self):
rect = self.x1 * self.x2
print(f"사각형의 넓이는 {rect}(단위없음)입니다.")
bdy = Rectangle(int(input("width: ")), int(input("height: ")))
# input().split()으로 한 번에 두 개의 입력을 넣으려면,
'''
Rectangle클래스는 두 개의 인자를 필요로 하므로 Rectangle(input, input)처럼 각각 전달해야함.
input().split은 리스트 하나를 반환하기 때문에 그대로 쓰면 인자 개수가 맞지 않아서 에러가 발생함.
w, h = map(int, input("width, height: ").split()) # map(int, ....): 문자열을 정수로 변환
bdt = Rectangle(w, h) # w, h: 각각 width, height로 할당됨
'''
bdy.area()
결과

class Dog:
# 클래스 변수
kind = "강아지"
def __init__(self, species, name, age):
self.species = species
self.name = name
self.age = age
dog1 = Dog("포메라니안", "리치", 12)
dog2 = Dog("비숑", "구름", 10)
print("인스턴스1", dog1.kind)
print("인스턴스2", dog2.kind)
print("클래스", Dog.kind)
class Book2:
book_count = 0
def __init__(self, title, author):
Book2.book_count += 1
self.title = title
self.author = author
# 클래스 메서드
@ classmethod # 데코레이터
def get_count(cls):
print(f"현재 {cls.book_count}권의 책을 가지고 있다.")
book1 = Book2("B1", "author1")
book2 = Book2("B2", "author2")
print(Book2.book_count)
Book2.get_count()
class OperationTool:
@staticmethod # 데코레이터
def add(a, b):
return a + b
print(OperationTool.add(10, 20))
class User:
username = 0
points = 0
total_users = 0
def __init__(self, username, points):
self.username = username
self.points = points
User.total_users += 1
def add_points(self, amount):
self.points += amount
def get_level(self):
if self.points >= 0 and self.points <= 99:
print(f"{self.username} / Tier: Bronze")
elif self.points >= 100 and self.points <= 499:
print(f"{self.username} / Tier: Silver")
elif self.points >= 500:
print(f"{self.username} / Tier: Gold")
elif self.points < 0:
print(f"{self.username} / Iron(심해)")
@classmethod
def get_total_users(cls):
print(f"생성된 전체 유저 수: {cls.total_users}")
gamer1 = User("Dongyun2", 1000)
gamer2 = User("배칠수의 꽃배달", 200)
gamer3 = User("신바람 이박사", 99999)
gamer1.get_level()
gamer2.get_level()
gamer3.get_level()
User.get_total_users()
결과

# 접근 제어와 정보 은닉
# 데이터 무결성을 보호하기 위함
# 코드 안정성을 향상 시키기 위함
class Person2:
def __init__(self, name, age):
# public
self.name = name
# private: 언더바(__) 두 개를 변수 앞에 붙여서 정의
self.__age = age
# getter
def get_age(self):
return self.__age
# setter
def set_age(self, value):
if value > 120 or value < 0:
print("유효하지 않은 나이입니다.")
else:
self.__age = value
p1 = Person2("lee", 15)
print(p1.name)
#print(p1.__age)
print(p1.get_age())
p1.set_age(-10)
class Ex:
def __init__(self):
self.value = 0
# getter
@property
def value(self):
return self.__value
# setter
@value.setter
def value(self, val):
if val < 0:
print("우효하지 않는 값입니다.")
else:
self.__value = val
ex1 = Ex()
print(ex1.value)
ex1.value = 100
print(ex1.value)
ex1.value = -100
print(ex1.value)
class UserAccount:
def __init__(self, username, password):
# 생성자에서 사용자 이름과 비밀번호 초기화(0으로 초기화하는 것이 아님;;)
self.username = username
self.__password = password # private으로 선언
def change_password(self, old_pw, new_pw):
if old_pw != self.__password:
print("비밀번호 불일치")
else:
self.__password = new_pw
print("비밀번호 변경됨")
def check_password(self, pw):
if self.__password == pw:
print(True)
else:
print(False)
# def check_password(self, password):
# return self.__password == password
bank = UserAccount("Dongyun2", 12345678) # 계좌 이용자, 비밀번호 입력
bank.change_password(12345678, 7777) # 비밀번호 7777로 변경
bank.check_password(775847) # 비밀번호 불일치 확인
bank.change_password(7777, 6666) # 변경된 비밀번호를 다른 비밀번호(6666)로 다시 변경
bank.change_password(1235, 77) # 비밀번호 불일치 유도
bank.check_password(6666) # 변경된 비밀번호 확인
# print(bank.username) # "Dongyun2"
# print(user.__password) # 출력안됨
결과

class Student:
def __init__(self, name, __score):
self.name = name
self.__score = __score
@property # getter
def score(self):
return self.__score
@score.setter # setter
def score(self, value):
if 0 <= value <= 100:
self.__score = value
else:
raise ValueError("성적은 0에서 100 사이여야 합니다.")
s1 = Student("Alice", 85)
print(s1.name)
print(s1.score) # 85
# s1.score = 105 # ValueError
s1.score = 95
print(s1.score) # 95
결과
class Animal:
def __init__(self, name):
self.name = name
def bark(self):
print("동물이 울음소리를 냅니다.")
# 자식 클래스
class Dog(Animal):
pass
dog = Dog("구름이")
dog.bark()
print(dog.name)
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("동물이 울음소리를 냅니다.")
# 자식 클래스
class Dog(Animal):
def __init__(self, name, age, species):
# super는 부모를 가리킴
super().__init__(name, age)
self.species = species
# 오버라이딩
def bark(self):
super().bark()
print("월월이청청")
dog = Dog("구름이", 17, "포메라니안")
dog.bark()
print(dog.name)
print(dog.age)
print(dog.species)
class Shape:
def __init__(self, sides, base):
self.sides = sides
self.base = base
def printinfo(self):
print(f"변의 개수: {self.sides}")
print(f"밑변의 길이: {self.base}")
def area(self):
print("넓이 계산이 정의되지 않았습니다.")
class Rectangle(Shape):
def __init__(self, sides, base, height):
self.sides = sides
self.base = base
self.height = height
# 오버라이딩
def area(self):
print(f"사각형의 넓이: {self.base * self.height}")
class Triangle(Shape):
def __init__(self, sides, base, height):
self.sides = sides
self.base = base
self.height = height
# 오버라이딩
def area(self):
print(f"삼각형의 넓이: {(self.base * self.height) /2}")
# 실행
shape = Shape(20, 7)
shape.printinfo()
shape.area()
rect = Rectangle(4, 10, 17)
rect.printinfo()
rect.area()
tri = Triangle(3, 15, 13)
tri.printinfo()
tri.area()
결과

from abc import ABC, abstractmethod # abc에서, ABC, abstractmethod를 가져와라.
class Animal(ABC):
# 추상 메서드
@abstractmethod
def bark(self): # 자식 클래서에서 모조건 구현을 하라고 강제하는거임
pass
class Dog(Animal):
def bark(self):
print("멍멍")
# a = Animal()
a = Dog()
a.bark()
class Payment(ABC):
# 추상 메서드
@abstractmethod
def pay(self, amount):
pass
class CardPayment(Payment):
def pay(self, amount):
print(f"카드로 {amount}원을 결제합니다.")
class CashPayment(Payment):
def pay(self, amount):
print(f"현금으로 {amount}원을 결제합니다.")
money = CardPayment()
money.pay(10000000000000000000000)
moneyyyy = CashPayment()
moneyyyy.pay(2398623946912837612984986748498487)
결과
