클래스

최조니·2022년 3월 26일
0

Python

목록 보기
11/12

클래스 (class)

  • 클래스 (Class)
    - 객체를 만들어 내기 위한 Type
    - class 키워드를 사용하여 새로운 클래스 작성
    - 파이썬 method의 첫번째 파라미터명은 관례적으로 self라는 이름 사용
    - class 키워드를 사용하여 새로운 클래스 작성

    Ex.

    ```
    class Person():
    	def __init__(self, name, age): # 호출하는 지점에서 값을 받아올검밍
        	self.name = name
          	self.age = age
    	#        
    	# address를 동적으로 초기화하는 함수를 정의
      	def set_address(self, address):
          	self.address = address
      	#
      	def info(self):
          	print(f"당신의 이름은 {self.name}이고 나이는 {self.age}입니다.")

    # main
    p1 = Person('John', 25)
    p1.info()
    p2 = Person('James', 24)
    p2.info()
    ```
    
    ㄴ> 출력값
    ```
    당신의 이름은 John이고 나이는 25입니다.
    당신의 이름은 James이고 나이는 24입니다.
    ```

  • 클래스변수, 전역변수 사용
    - 클래스 변수는 클래스 선언 바로 아래에 변수를 선언하면 됨
    - 클래스명.변수명 으로 접근하여 사용

    Ex.

    ```
    class KBStudent:
    	count = 0  		# 클래스 변수 : 생성된 객체들이 이 변수를 공유함 
    	def __init__(self, name, python, django, deep):
        	self.name = name
        	self.python = python
        	self.django = django
        	self.deep = deep
        #
        KBStudent.count += 1
        print("{}번째 학생이 가입되었습니다.".format(KBStudent.count))
        #
    	def get_sum(self):
        	return self.python + self.django + self.deep
    	#
    	def get_avg(self):
        	return "{:.2f}".format(self.get_sum() / 3)
        #
    	# 정보를 리턴하거나 정보를 출력하는 기능 .. 별도로 작성 / __str__
    	# 오버라이딩 : 부모가 물려준 기능을 받아서 + 그걸 자식에게 맞게 고쳐쓴다
    	def __str__(self):
        	return "{}\t{}\t{}\t".format(self.name, self.get_sum(), self.get_avg())
    #
    # ------------------- MAIN -----------------------
    students = [
    	KBStudent("강호동", 87, 90, 68),
    	KBStudent("민경훈", 90, 90, 60),
    	KBStudent("이수근", 98, 79, 80),
    	KBStudent("서장훈", 80, 80, 90)
    ]
    # 정보출력
    print("이름\t총점\t평균")
    for st in students:
    	print(st)    
    print(f"현재까지 가입한 총 학생 수는 {KBStudent.count}명 입니다.")
    ```
    
    ㄴ> 출력값
    ```
    1번째 학생이 가입되었습니다.
    2번째 학생이 가입되었습니다.
    3번째 학생이 가입되었습니다.
    4번째 학생이 가입되었습니다.
    이름	총점	평균
    강호동	245	81.67	
    민경훈	240	80.00	
    이수근	257	85.67	
    서장훈	250	83.33	
    현재까지 가입한 총 학생 수는 4명 입니다.
    ```

  • 객체 생성과 소멸

    Ex.

    ```
    class Programmer:
    	def __init__(self, name, birthday, salary, tech, bonus):
        	self.name = name
            self.birthday = birthday
            self.salary = salary
            self.tech = tech
            self.bonus = bonus
        def __del__(self):
        	print('인스턴스가 소멸됩니다.')
    ```

  • 상속
    - 확장성 있는 프로그램을 작성하는 일반적인 도구
    - 새로운 매소드 추가 / 인스턴스에 새로운 속성 추가 / 기존 메소드 일부를 재정의(redefine, overriding) 가능
    - 위 작업은 기존 클래스를 확장(상속)함으로 손쉽게 얻어질 수 있음

    Ex.

    ```
    class Birthdate:
    	def __init__(self, year, month, day):
        	self.year = year
        	self.month = month
        	self.day = day 
    	def get_date(self):
        	return self.year,self.month, self.day
    #
    # -------------------- Parent Class : Employee --------------------
    class Employee:
    	total_count = 0
    	def __init__(self, name, birthdate, salary):
        	self.name = name
        	self.birthdate = birthdate
        	self.salary = salary
    		#            
        	Employee.total_count += 1
    	#
    	def show_info(self):
        	print(f"이름 : {self.name}, 생년월일 : {self.birthdate.get_date()}, 급여:{self.salary}", end='')
    #
    # ------------------- Child Class : Manager -----------------------
    class Manager(Employee): # Manager은 자식 클래스, Employee는 부모 클래스    
    	def __init__(self, name, birthdate, salary, dept):
        	super().__init__(name, birthdate, salary)
        	self.dept = dept 
    	#
    	def show_info(self):
        	super().show_info()
        	print(f", 부서 : {self.dept} 입니다")
    #
    # ------------------- MAIN -----------------------
    m = Manager("김연아", Birthdate(1988, 1, 1), 3000000, 'IT')
    m.show_info()
    ```
    
    ㄴ> 출력값
    ```
    이름 : 김연아, 생년월일 : (1988, 1, 1), 급여:3000000, 부서 : IT 입니다
    ```

  • 다중상속
    - class Child(Parent1, Parent2): 로 Child class에 Parent1, Parent2 class 상속
    - 먼저 나온 Parent class가 우선순위를 가짐

    Ex.

    ```
    class Mother:
    	def work(self, info):
        	print(f"{info} .... work ....")
    ##  
    class Father:
    	def work(self, info):
        	print(f"{info} .... work ....")
    ##            
    class Me(Mother, Father):
    ```
profile
Hello zoni-World ! (◍ᐡ₃ᐡ◍)

0개의 댓글