현대오토에버 모빌리티 sw 스쿨 3기 [클라우드]/PYTHON

OOP. Python 강의 / 모빌리티 SW 스쿨 / 클라우드반

맹꽁이+ 2025. 12. 23. 09:06

OOP 코딩 공부 github: https://github.com/dlcodns/PythonPrograming/blob/main/practice/5_OOP.py

 


 

캡슐화(Encapsulation)

  • 자료 추상화(Data Abstraction): 불필요한 정보는 숨기고 중요한 정보만을 표현하여 프로그램 단순화
  • 추상 자료형(Abstract Data Type, ADT): 자료 표현과 연산을 캡슐화한 자료형, 접근 제어를 통해 정보 은닉 가능
  • OOP 용어
    • ADT → 클래스
    • ADT의 인스턴스 → 객체
    • ADT의 정의된 연산 메서드(클래스 내 함수)
    • 인스턴스 생성을 위해 호출하는 메서드  생성자

상속(Inheritance)

  • 상위 클래스의 모든 요소를 하위 클래스가 물려 받는 것
    • 하위 → 상위(하위에 똑같이 있는 것을 끌어 올렸다)
  • 상속의 목적
    • 중복 제거
    • Framework Library 사용: 특정 부분만 오버라이딩, 생산성 극대화

다형성(Polymorphism)

  • 객체마다 다르게 반응하는 성질
  • EX) 마우스로 클릭할 때, 선택, 하이퍼링크 등 다르게 반응

추상화(Abstract)

  • 핵심만 보여주고, 내부는 숨겨 단순하게 만드는 것

클래스 속성 접근

  • 클래스 내에 정의된 속성(값)에 접근하는 것
class Student:
    school = "CBNU"  # 클래스 속성
    
print(Student.school)    # 클래스 속성 접근

객체 속성 접근

  • 각 인스턴스가 개별적으로 보유한 속성에 접근하는 
class Student:
    def __init__(self, name):
        self.name = name  # 객체 속성
        
s1 = Student("홍길동")
s2 = Student("김철수")

print(s1.name)   # 홍길동
print(s2.name)   # 김철수

 

 

데코레이터

 

@staticmethod

@classmethod

 

 


__slot__

  • 이 attribute에 list로 attribute을 나열하면 나열한 attribute만 사용이 가능하고 새로운 attribute은 생성 불가능
  • 이걸 정의하면 __dict__ 사용 불가능
class Student:
    __slots__ = ["name", "score"]

student = Student()
student.name = "제시카"
student.score = 90
student.tel = "01031391997"
print(student.tel)

#오류 메시지: AttributeError: 'Student' object has no attribute 'tel' and no __dict__ for setting new attributes

 

private 설정

  • 속성을 생성할 때 __ 추가하면 private 속성이 됨.

property

  • getter 와 setter Method를 호출하는 것으로 처리되는 Attribute
  • 변수명 = property(fget=None, fset=None, fdel=None, doc=None)
class Student:
    def __init__(self,name, age):
        self.name = name
        self.__age = age

maria = Student("마리아", 20)
maria.name = "Maria"
maria.__age -= 1
#오류 메시지: private을 수정하려고 해서. AttributeError: 'Student' object has no attribute '__age'

↓ 완성 코드

  • 직접 호출이 아닌 property 처리한 age를 
class Student:
    def __init__(self,name="noname", age=20):
        self.name = name
        self.__age = age

    def setAge(self, age):
        print("Setter 호출")
        self.__age = age

    def getAge(self):
        print("getter 호출")
        return self.__age
    
    age = property(getAge, setAge)

stu = Student()
stu.age = 30
print(stu.age)