oop
Object-Oriented Programming
객체지향 프로그래밍
데이터 보호가 목적으로 필드에 접근 제한을 설정함
pricate 비공개, 캡슐화
public 공개
protected 상속시 후손에게만 공개
파이썬은 접근 제한자가 없고 기본적으로 클래식 안의 모든 멤버는 public임
파이썬에서 클래스 멤버를 private처리하려면 __ 접두사를 사용한다.
class PClass:
__num = 10 # 정적 변수
def __init__(self): # 생성자
self.__num = 0
def __init__(self, num): # 생성자
self.__num = num # 오버라이딩
def set_num(self, num):
self.__num = num
def get_num(self):
return self.__num
pref = PClass(2)
print(pref.get_num())
Java와 같은 다른 언어들과 다르게 Python은 같은 함수 오버로딩을 지원하지 않는다.
https://standout.tistory.com/192
생성자가 두개, Overloading
생성자가 두개이상일때 생성자 Overloading라고 한다. 서로다른 매개변수가 여러개 적재될 수 있다. public MyClass() { this.name = "Default"; } public MyClass(String name) { this.name = name; }
standout.tistory.com
정적변수를 오버라이딩해 원하는 값으로 초기값설정할 수도 있고

매개변수를 추가해 입력받은 값으로 세팅해줄 수도 있다.

오버로딩을 지원하지않는 파이썬은 생성자가 두개일경우 덮어쓴다.


def __del__(self)
객체가 삭제될때 자동실행됨

class Var:
__number = 100
def __init__(self, num):
self.__number = num
def __del__(self):
print("인스턴스 제거시 자동 호출됨", id(self))
def get_number(self):
return self.__number
def set_number(self, num):
self.__number = num
v1 = Var(100)
print('v1',v1.get_number(), id(v1))
v2 = Var(200)
print('v2',v2.get_number(), id(v2))
# del v1
print("--- 프로그램의 모든 코드가 종료되었습니다 ---")
del을 명령하지 않더라도 객체들은 삭제되는데
이는 파이썬 프로그램이 종료될 때 메모리를 자동으로 청소하기 때문이다.

set_number() 값변경, 주소는 그대로이고 값만 바뀌는것을 확인

정적메소드
static method
정적메모리에 따로 기록되는 메소드, 사용시 객체 레퍼런스 없이 실행한다. = self가 없는 메소드
class C:
def ham(self, x, y):
print('instance method ham', x, y, id(C), id(self))
class D:
@staticmethod
def spam(x, y):
print('static method spam', x, y, id(D))
c = C()
d = D()
c.ham(1, 2)
d.spam(3, 4)


https://standout.tistory.com/1677
TypeError: D.spam() missing 1 required positional argument: 'y' : feat. 정적 메소드(Static Method)와 인스턴스 메소
파이썬에서 @staticmethod에 self를 출력하려고 하면 타입에러가 뜬다 . File "g:\study\sk_playdata\study_ai\python_workspace\day5_python_oop\class_oop.py", line 57, in d.spam(3, 4) ~~~~~~^^^^^^TypeError: D.spam() missing 1 required positio
standout.tistory.com
파이썬은 실행할때 동적으로 멤버 변수를 추가할 수 있다.
이때 주의점은 '해당 실행하는 인스턴스안에' 추가하는 것이지 class에 추가되는것은 아니다.


오버로딩
오버라이딩
오버로딩은 '과적: 과하게 싣다'라는 의미로 같은 이름의 메소드를 여러개 만드는 행동이다.
오버라이딩은 '재정의: 덮어쓰다'라는 의미로 부모의 메소드를 자식이 다시 만드는 행동이다 .
https://standout.tistory.com/192
생성자가 두개, Overloading
생성자가 두개이상일때 생성자 Overloading라고 한다. 서로다른 매개변수가 여러개 적재될 수 있다. public MyClass() { this.name = "Default"; } public MyClass(String name) { this.name = name; }
standout.tistory.com
https://standout.tistory.com/160
덮어쓰는 annotation, @Override
@ annotation 컴파일 주석기호 @Override 재정의, 부모의 말을 덮어쓰기/거역하다로 이해해보자. 인터페이스등을 implements하면 자주 보게 될것이다. VIP고객에게 일반고객과 같은 안내문자를 보내지만
standout.tistory.com
최우선 연산자 () []
단항연산자 + - ++ -- ! ~
이항연산자 * / // % ** + - << >> > < >= <= == != amd xor or
삼항연산자 조건식 ? 참 : 거짓
대입연산자 = += -= *= /= //= %= **=
나열연산자 ,
상식적으로 생각해보면 쉬운 연산자들

https://standout.tistory.com/1147
자바의 정석 Chapter03: 연산자
들어가기전에, 연산자에 대해 배워갈때 알고있어야하는점은, 연산자의 종류는 기술/코딩의 발전에 따라 그 종류가 방대하기에 한번에 학습하기를 목표로 하기보다는 자주 사용하는 연산자를
standout.tistory.com
https://standout.tistory.com/64
비트연산자, &|^~<<>>
비트연산자 &(엔터샌드 AND) |(파이프 OR) ^(캐럿 XOR) ~(틸데 NOT) A B: A를 B만큼 옮기겠다 &(엔터샌드 AND) 두 비트가 모두 1인 경우 1을 반환하고, 그 외에는 0을 반환. 논리 AND 연산과 비슷한 개념 |(파이
standout.tistory.com
https://standout.tistory.com/827
php 조건삼항연산자, 조건 ? A:B
조건삼항연산자 참일때 앞, 거짓일때 뒷값이 출력된다. 조건 ? 참일 때 값 : 거짓일 때 값 예시코드
standout.tistory.com
객체지향프로그래밍의 대표적인 예 계산기
class OOP:
__num = 0
def __init__(self, num):
self.__num = num
def __add__(self, value):
return self.__num + value
def __sub__(self, value):
return self.__num - value
def __mul__(self, value):
return self.__num * value
def __truediv__(self, value):
return self.__num / value
def get_num(self):
return self.__num
def set_num(self, num):
self.__num = num
ref = OOP(100)
print(ref.get_num())

https://standout.tistory.com/14
객체와 객체지향프로그래밍 OOP
객체 Object 객체는 깔끔하게 정의내리기 어렵다. 이해가 힘들다면 '나를 제외한 모든 것'이라고 이해하고 넘어가보자. 객체란 하나의 역할을 수행하는 '메소드와 변수(데이터)'의 묶음으로, 정의
standout.tistory.com
https://standout.tistory.com/1156
자바의 정석 Chapter06: 객체지향 프로그래밍
객체지향이론 실제세계는 객체로 이루어져있으며 실제 세계를 컴퓨터 속에 옮겨놓은 것과 같은 가상 세계를 구현해 실험함으로써 많은 시간과 비용을 절약한다 https://standout.tistory.com/14 객체와
standout.tistory.com
https://standout.tistory.com/1157
자바의 정석 Chapter07: 객체지향 프로그래밍
상속 extends 기존의 클래스를 재사용하여 새로운 클래스르 작성하는것. https://standout.tistory.com/157 상속받다, extends 상속받다, extends 상속 extends 확장하다 이미 작성된 클래스를 기반으로 새로운 클
standout.tistory.com
오버로딩으로 함수를 어떻게 덮어쓰기 할 수 있는지 확인해보자.
실제 len은 리스트가 아닌 객체에서 에러를 뽑아내지만 그저 self를 반환하라고 오버로딩한 코드를 타니
에러없이 본인을 반환하고 있다 .


in 연산자도 마찬가지

인덱싱도 마찬가지, 연산자 오버로딩이 가능하다.
해당 객체 안에 시퀀스가 들어있어 접근해야하지만 이런식으로 오버로딩하면 바로 인덱싱에 접근할 수 있음을 확인했다.


상속
부모 클래스의 기능을 물려받아 새로운 클래스를 만들음
코드 중복을 줄이고 재사용성을 높이는 것이 목적
class 자식(부모): 로 만듬, 부모 메서드를 다시 작성함.

https://standout.tistory.com/157
상속받다, extends
상속받다, extends 상속 extends 확장하다 이미 작성된 클래스를 기반으로 새로운 클래스를 작성하고 확장할 수 있다. 이때 extends한 하위클래스 호출시, 상위클래스가 호출된 이후 상속받은 하위클
standout.tistory.com
super()를 사용할 경우 부모 메서드를 끌어다 사용해 return 할 수 있다.

# overriding
class Animal:
def speak(self):
print("animals sound like")
class Dog(Animal):
def speak(self):
print("bow wow")
class Cat(Animal):
def speak(self):
print("meow meow")
class Reset(Animal):
def speak(self):
return super().speak()
animal = Animal()
animal.speak()
dog = Dog()
cat = Cat()
reset = Reset()
dog.speak()
cat.speak()
reset.speak()
https://standout.tistory.com/158
this 와 super
this = 부모의 멤버변수 super = 생성자(부모) this 부모의 멤버변수 getter setter에서 많이볼 수 있는데 생성자의 멤버변수를 가리킬때 자주사용된다. public class MyClass { private int num; public MyClass(int num) {
standout.tistory.com
다형성
같은 메서드 이름인데 참조 객체에 따라 따라 다른 동작을 하는 경우

+
day 4에서 못했던 exception을 이어서 스터디.


except는 여러개일 수 있다.

for문과 pass를 활용해 에러가 나도 무시하고 진행할 수도 있다.

ef except_pass():
lst = ['3', '예외처리', '2', '1']
digit_num = []
for idx in range(len(lst)):
try:
digit_num.append(int(lst[idx]))
except ValueError:
pass
print(digit_num)
except_pass()
try, except, else ,finally
try: # 에러 발생 가능 코드
except: # 에러 발생 시 실행
else: # 에러 없을 때 실행
finally: # 무조건 실행
try를 확인해보면 for문에 맞춰 코드가 실행될때 수행되고있다.

except때를 보면 pass를 적어놨기때문에 pass된것을 확인 할 수 있다.

else는 에러가 아닐경우임으로총 3번 출력되는것을 확인할 수 있다.

finally는 언제나 실행되어야함으로 4번 출력됨을확인할 수 있다.

def except_pass():
lst = ['3', '예외처리', '2', '1']
digit_num = []
for idx in range(len(lst)):
try:
digit_num.append(int(lst[idx]))
print('try: ', digit_num)
except ValueError:
pass
else:
print('else: ', digit_num)
finally:
print('finally: ', digit_num)
print(digit_num)
except_pass()
import math
def test_finally():
관련 예제로 한번 더 경험


import math
def test_finally():
try:
radius = float(input("반지름을 입력하세요: "))
except ValueError:
print("반지름을 입력하세요.")
except Exception as e:
print(e)
else:
print('반지름: ', radius)
print('원면적: ', math.pi * math.pow(radius, 2))
finally:
print('구문종료')
test_finally()'SK 네트웍스 AI 캠프' 카테고리의 다른 글
| SK 네트웍스 AI 캠프 - 1_프로그래밍 데이터 기초 - Day7_파이썬 Streamlit GUI 웹프로그래밍 (0) | 2026.05.08 |
|---|---|
| SK 네트웍스 AI 캠프 - 1_프로그래밍 데이터 기초 - Day6_파이썬 모듈과 패키지 (0) | 2026.05.07 |
| SK 네트웍스 AI 캠프 - 1_프로그래밍 데이터 기초 - Day4_파일입출력_예외처리 (0) | 2026.05.04 |
| [SK네트웍스 Family AI 캠프] 32기 1주차 회고 (0) | 2026.05.04 |
| SK 네트웍스 AI 캠프 - 1_프로그래밍 데이터 기초 - Day3_파이썬 함수 (0) | 2026.04.30 |