반응형

클래스란 ?

 

- 객체의 구조를 나타낸다.

- 클래스에 의해 만들어진 객체를 인스턴스라고도 부른다.

 

 

객체와 인스턴스의 차이

- 객체는 클래스 정의시 메소드 밖에 존재하며, 클래스명.변수명 으로 사용한다. 

- 인스턴스는 메소드 안에서 사용하며, self.변수명으로 사용한다.

 

# 모듈의 멤버로 클래스

class TestClass:
    kk = 1 # 멤버변수 ( 전역 )
    
    def __init__(self):
        print('생성자')
        
    def __del__(self):
        print('소멸자')
        
    def printMsg(self): # 메소드 (public)
        name = '한국인' # 지역변수
        print(name)
        print(self.kk)
        
test = TestClass() # 생성자 호출. instance
print(test.kk) # 1을 출력
print(TestClass.kk) # prototype(원형) 클래스의 멤버 직접 호출
 
print()

test.printMsg() # Bound Method call
# TestClass.printMsg() # 이렇게 주면 아규먼트를 주지 않아서 ERR
print()
TestClass.printMsg(test) # UnBound Method call


출력 결과

생성자
1
1

한국인
1

한국인
1

소멸자

 

# Bound Method Call는 self가 붙은 쪽에 사용하고, UnBound Method Call 이란 self 를 안 붙은 쪽을 말합니다.

 

파이썬에서 사용하는 특별한 메소드

 

# __init__ : 

- 초기화(initialize) 메서드라고도 합니다.

- 어떤 클래스의 객체가 만들어질 때 자동으로 호출되어서 그 객체가 갖게 될 여러 가지 성질을 정해주는 역할을 함

- 위 소스에서는 TestClass() 를 작성하여 TestClass 객체를 생성하자마자 초기화가 되고 '생성자'를 출력하였습니다.

 

# __del__ :

- 객체가 없어질때 사용하는 메소드입니다.

- 위 소스에서는 그래서 맨 마지막에 '소멸자'가 출력되었습니다.

 

 

 

이번에는 __init__ 메소드에 인자를 받아야만 생성자가 생성되는 예제를 들어보겠습니다.

 

class Car:
    handle = 0
    speed = 0

    def __init__(self, name, speed):
        self.speed = speed
        self.name = name
        
    def showData(self):
        km = '킬로미터'
        msg = '속도:' + str(self.speed) + km
        return msg
    
print(Car.handle)
print(Car.speed)
#print(Car.name) # type object 'Car' has no attribute 'name'
print()
car1 = Car('tom',10)
print(car1.handle, car1.name, car1.speed)
print('------')
car2 = Car('james',20)
print(car2.handle, car2.name, car2.speed)

print()
print(car1.showData())
print(car2.showData())
car1.speed = 88
car2.speed = 100
print(car1.showData())
print(car2.showData())

Car.handle = 1
print(car1.handle)
print(car2.handle)


출력 결과

0
0

0 tom 10
------
0 james 20

속도:10킬로미터
속도:20킬로미터
속도:88킬로미터
속도:100킬로미터
1
1

 

위 소스코드는 __init__ 생성자에 self, name, speed 를 주었기 때문에 새로운 객체를 생성할때 name,과 speed를 가지고 가야 생성이 가능합니다. 그렇지 않으면 다음과 같은 에러를 출력합니다.

 

 

car1 객체와 car2 객체를 생성 한 후에는 speed 값을 기존 10에서 각각 88과 100으로 변경해주었습니다.

그 출력 결과 속도들의 변경된 점을 확인 가능했습니다.

 

# 클래스는 포함자원의 재활용 목적으로 다른 클래스를 불러다가 사용 가능합니다.

 

handle.py

 

# 다른 클래스에서 공유할 클래스

class PohamHandle:
    quantity = 0
    
    def LeftTurn(self, quantity): # self에 quantity 가 들어옴
        self.quantity = quantity
        
        return '좌로 돌아';
    
    def RightTurn(self, quantity): # self에 quantity 가 들어옴
        self.quantity = quantity
        
        return '우로 돌아';

 

PohanCar.py

 

import etc.handle

class PohanCar:
    turnShow = '정지'
    
    def __init__(self, ownerName):
        self.ownerName = ownerName
        self.handle = etc.handle.PohamHandle()
        
        
    def TurnHandle(self, q):
        if q > 0:
            self.turnShow = self.handle.RightTurn(q)
        elif q < 0:
            self.turnShow = self.handle.LeftTurn(q)
        else:
            self.turnShow = '직진'
            
if __name__ == '__main__':
    tom = PohanCar('tom')
    tom.TurnHandle(10)
    print(tom.ownerName + ' 의 회전량은 ' + tom.turnShow + str(tom.handle.quantity))            
    
    print()
    james = PohanCar('james')
    james.TurnHandle(0)
    print(james.ownerName + ' 의 회전량은 ' + james.turnShow + str(james.handle.quantity))

 

출력 결과

 

반응형

'python' 카테고리의 다른 글

python - 상속 (2)  (0) 2020.05.10
python - 상속  (0) 2020.05.10
python - 재귀함수  (0) 2020.05.10
python - 함수 장식자 ( Decorator )  (0) 2020.05.10
python - 파이썬은 1급 함수인가 ?  (0) 2020.05.08

+ Recent posts