Lecture 강의

Undergraduates 학부 Graduates 대학원 Lecture 역학 Lecture 설계 Lecture IT(IoT, AI) Lecture SAP2000 Lecture 아바쿠스 Lecture 파이썬 Lecture 엑셀 VBA Lecture 마이다스 Lecture 이탭스

[02. 문법] 2.5 클래스 - class, 객체, 상속, 매서드, 생성자, self, 멤버변수, 다중 생성, 정적함수

작성자 : kim2kie

(2023-02-19)

조회수 : 1074

[참조]

 

간단한 프로그램은 함수만으로 효율적인 절차지향(procedure-oriented) 프로그래밍을 작성할 수 있다.
하지만 프로그램이 커지면 객체의 틀(뼈대)인 클래스(class)를 사용한 객체지향(object-oriented) 프로그래밍이 필요하다.

(1) 클래스와 객체
(2) 클래스의 정의: class
(3) 클래스의 상속(inheritance)
(4) 정적함수를 이용한 다중 생성


 

(1) 클래스와 객체 

  • 과자 틀 → 클래스(class)
    과자 틀에 의해서 만들어진 과자 → 객체(object)

     
  • 인스턴스(instance)
    클래스(class)를 이용하여 생성된 객체(object)를 의미한다. 
    즉, 인스턴스는 클래스를 통해 정의된 속성(attribute)과 메서드(method)를 가진 객체를 의미한다. 

 

 

(2) 클래스의 정의: class 

방법 1)

  • class 키워드를 이용해 클래스를 선언한다.
  • 클래스로 객체를 생성한 후에 변수와 함수를 하나씩 추가한다.
     
  • Ex)
    class Simple: # 클래스 Simple의 선언
        pass

    # 정의한 클래스의 객체를 생성한 후 멤버변수를 추가할 수 있다.

    a = Simple() # 클래스 Simple의 객체 a 생성
    a.name = 'Jane' # 객체 a의 멤버변수 name 추가
    a.phone = '123-456-7890' # 객체 a의 멤버변수 phone 추가

 

방법 2)

  • class 키워드를 이용해 클래스를 선언한다.
  • 클래스에 변수와 함수를 한 번에 정의한다.
     
  • Ex)
    class Account: # 클래스 Account의 선언
        numOfAccount = 0 # 변수
        def __init__(self,name): # 생성자 함수 정의
            self.name = name; # 객체 변수 name
            self.balances = 0 # 객체 변수 balances
            Account.numOfAccount += 1 
        def withdraw(self,value): # withdraw 함수 정의
            self.balances -= value
            return self.balances
        def deposit(self,value): # deposit 함수 정의 
            self.balances += value        
            return self.balances
        def __del__(self): # 소멸자 함수 정의
            Account.numOfAccount -= 0

    a1 = Account('John') # 클래스 Account의 객체 a1 생성
                   # 객체 a1의 변수 name에 John을 할당
    a1.deposit(10) # 객체 a1의 함수 deposit를 사용하여 10을 적립: balances = 0 + 10 = 10
    a1.withdraw(2) # 객체 a1의 함수 withdraw를 사용하여 2을 인출: balances = 10 - 2 = 8
    print(a1.balances) # 8

    a2 = Account('Jane') # 클래스 Account의 객체 a2 생성
                   # 객체 a1의 변수 name에 Jane을 할당
    print('no of Account : ',Account.numOfAccount) # 2

     

  • 함수에 self 인자가 없는 경우는 C의 static member와 동일하다. 

 

  • 이 함수에서는 클래스 멤버변수를 조작하거나 단순히 namespace를 사용하는 함수처럼 사용해야 한다.
     
  • Ex)
    class Account:
        numOfAccount = 0
        def makeZero(number):
            Account.numOfAccount = number

     
  • 매서드(method, 매소드) 
    클래스 내에서 정의되는 함수(function)이다.
    기본함수가 아닌 사용자 정의 함수이다.
  • 생성자(constructor) 메서드(함수): __init__
     객체가 생성될 때 자동으로 호출되며, 인스턴스(객체) 변수의 초기화를 수행한다. def __init__(파라미터): 를 통해 작성한다.
  • self
    클래스에서 self는 현재 인스턴스를 나타내는 첫 번째 매개변수로써, 관례적으로 사용되는 이름이다. 
     즉, 파이썬에서 클래스를 정의할 때 메서드의 첫 번째 매개변수는 반드시 self이어야 한다.
    이는 해당 클래스의 인스턴스를 전달받아 해당 인스턴스의 속성이나 메서드에 접근할 수 있도록 하기 위함이다.
  • 속성(property) 
    멤버변수와 함수는 public 속성을 지닌다.
    만약 private 속성으로 할 때는 두개의 밑줄 __로 시작한다.
  • 멤버변수(member variable): self.내부변수명
    클래스 내부변수이다. 생성자에서 선언한다.

 

 

(3) 클래스의 상속(inheritance)

  • 상속(inheritance)이란
    부모 클래스(parent class; super class)의 속성(property)과 함수(method)를 
    자녀 클래스(child class)가 그대로 물려 받는 개념이다.

     
  • Ex)
    class Element: # 부모 클래스 Element의 선언
        def __init__(self,id): # 생성자 함수
            self.id = id
            self.nodeIds = []
        def computeStiffness(self): # 함수 생성
            print('Element::computeStiffness')
        def printElement(self): # 함수 생성
            print('id : %d'%self.id)        

    class Q4Element(Element): # 부모 클래스 Element를 상속한 자녀 클래스 Q4Element의 선언
        def __init__(self,id,nodeIds): # 생성자 함수
            super().__init__(id)  # 또는 Element.__init__(self,id)
            self.nodeIds = nodeIds
        def computeStiffness(self):
            print('Q4Element::computeStiffness')

     

    # 자녀 클래스에서 부모 클래스의 생성자인 __init__()를 호출하는 방법은 다음 두 가지가 있다. 
    #  방법 1) super().__init__(id) 등과 같이 self를 사용하는 방법
    #  방법 2) Element.__init__(self,id)와 같이 클래스 이름을 사용하고 함수에 self를 사용하는 방법

     

    e = Q4Element(1,[1,2,3]) # # 클래스 Q4Element의 객체 e 생성
    e.printElement()  # 객체 e의 멤버변수 printElement 함수를 실행. 결과) id : 1
    e.computeStiffness() # 객체 e의 멤버변수 computeStiffness 함수를 실행. 결과) Q4Element::computeStiffness

 

(4) 정적함수를 이용한 다중 생성

  • 파이썬 클래스는 keyword 입력을 허용하기 때문에 다중 생성자(multiple constructors)를 쓰기 쉽지 않다. 
    이를 위해
    Ex1) variable(변동 가능한) 입력을 받든지,
    Ex2) 정적함수를 이용하는 방법을 사용할 수 있다.
  • 정적함수(static function) 
    함수의 실행이 클래스 외부 상태에 영향을 끼치지 않는 함수이다.

     
  • Ex1)
    class Rectangle:
        def __init__(self, *arg,**karg):
            ... 

     

  • Ex2)
    class Rectangle:
        def __init__(self):
            self.w = None
            self.h = None
        def fromWidthHeight(w,h):
            r = Rectangle()
            r.w = w
            r.h = h
            return r
        def fromArea(w,area):
            r = Rectangle()
            r.w = w
            r.h = area/w
            return r

    Rectangle.fromWidthHeight(4,10)
    Rectangle.fromArea(4,10)