[Python] 파이썬 클래스 (Class)

AhnHz·2023년 11월 25일
0

Python 기초

목록 보기
6/8
post-thumbnail

클래스 ( Class )

: 함수의 모임

  • 역할 : 다수의 함수와 공유 자료를 묶어서 객체 생성
  • 구성 : 멤버(member) + 생성자
  • 유형 : 사용자 정의 클래스, 내장 클래스
class 클래스명:
    멤버: 변수, 함수
    생성자: 객체 생성

클래스 생성

class Bicycle():
	pass

객체 생성 및 호출

my_bic = Bicycle()  # 객체 생성

my_bic.wheel_size = 26  # 객체 속성값 입력
my_bic.color = 'black'

print('바퀴 크기:', my_bic.wheel_size)  # 객체의 속성 출력
print('색상:', my_bic.color)

>>	바퀴 크기: 26
	색상: black



1. Method

: class에서 정의한 함수

메소드 유형

  • 객체 메소드 (instance method) : object.method() 호출, (self) 기본 인수
  • 클래스 메소드 (class method) : class.method() 호출, (cls) 기본 인수

객체 메소드 (instance method)

class Car():
   
    def __init__(self, size, color):  # 생성자. 객체 초기화
        self.size = size    # 인스턴스 변수 생성 및 초기화
        self.color = color  # 인스턴스 변수 생성 및 초기화
        
    def move(self):  # 인스턴스 메소드
        print("자동차({} & {})가 움직입니다.".format(self.size, self.color))
        
        
car1 = Car('small', 'white')  # 객체 생성
car2 = Car('big', 'black')

car1.move()  # 객체로 함수 호출
car2.move()

>>	자동차(small & white)가 움직입니다.
	자동차(big & black)가 움직입니다.

class cal_class:
    x = y = 0

    def __init__(self, a, b):
        self.x = a  
        self.y = b

    def plus(self):  # 멤버 함수(기능)
        p = self.x + self.y
        return p

    def minus(self):  # 멤버 함수(기능)
        m = self.x - self.y
        return m

obj1 = cal_class(10,20)  # 객체 생성
print('1)')
print('plus = ', obj1.plus())  # plus =  30
print('minus =', obj1.minus())  # minus = -10


obj2 = cal_class(100,50)
print('\n2)')
print('plus = ', obj2.plus())  # plus =  150
print('minus =', obj2.minus())  # minus = 50

>>	1)
	plus =  30
	minus = -10

    2)
    plus =  150
    minus = 50

클래스 메소드 (class method)

class DatePro:
    # 멤버 변수
    content = '날짜 처리 클래스'

    # 생성자
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

        
    # 객체 메소드
    def display(self):
        print('%d-%d-%d' %(self.year, self.month, self.day))

        
    # 클래스 메소드
    @classmethod # 함수 데코레이터. 클래스 메소드를 지정한다 (안하면 걍 객체 메소드처럼 실행)
    def date_string(cls, dateStr):  # 기본인수 cls. yyyymmdd
        year = dateStr[:4]
        month = dateStr[4:6]
        day = dateStr[6:]

        print(f'{year}{month}{day}일')
        

# 객체 멤버
date = DatePro(1945, 8, 15) 

print(date.content)
print(date.year) # 1945
date.display() # 1945-08-15

print()

#클래스 멤버
print(DatePro.content)
DatePro.date_string('19190301')

>>	날짜 처리 클래스
    1945
    1945-8-15

    날짜 처리 클래스
    19190301



2. 클래스 상속 (Inheritance)

기존 클래스를 이용하여 새로운 클래스 생성

  • 상속 대상: 멤버(변수+함수)
  • 생성자는 상속 대상이 아님
class 새로운 클래스(기존 클래스):
    멤버 변수
    생성자
    멤버 함수

# 부모 클래스
class Super:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print('name: %s, age: %d'%(self.name, self.age))


sup = Super('부모', 55)
sup.display()
# 자식 클래스
class Sub(super):
    gender = None

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def display(self):
        print('name: %s, age: %d, gender: %s'%(self.name, self.age, self.gender))


sub = Sub('자식', 25, '여자')
sub.display()

자식 클래스에서 부모 클래스의 생성자를 호출하기 위해 super() 클래스 사용

class Parent:

    def __init__(self, name, job):
        self.name = name
        self.job = job

    def display(self):
        print('name: {}, job: {}'.format(self.name, self.job))


class Child(Parent):
    gender = None

    def __init__(self,name,job,gender):
        super().__init__(name, job)
        self.gender = gender

    def display(self): # 함수 재정의. 메소드 오버라이딩. 다형성(Polymorphism)의 예
        print('name : {}, job : {}, gender : {}'
              .format(self.name, self.job, self.gender))
        

p = Parent('홍길동', '회사원')
p.display()        

c = Child('이순신', '장군', '남자')
c.display()

>>	name: 홍길동, job: 회사원
	name : 이순신, job : 장군, gender : 남자
profile
데이터 분석가 연습생입니다

0개의 댓글