Class
파이썬도 static stack heep 영역으로 나뉘어 있다.
새로운 class를 생성하고, 생성자와 메소드를 부여했다.
class Car:
handle = 0 # Car type의 객체에 참조 가능 멤버 필드
speed = 0
def __init__(self, name, speed):
self.name = name
self.speed = speed
def showData(self): # Car type의 객체에서 참조 가능 멤버 메소드
km = '킬로미터'
msg = '속도:' + str(self.speed) + km
return msg
print(id(Car))
print(Car.handle)
print(Car.speed)
2652749020752
0
0
만들어둔 Car type을 참조해서 객체를 생성하고 car1라는 객체변수에 담았다
car1 = Car('tom', 10) - Car의 생성자를 참조해 각각 car1->self, 'tom' -> name, 10-> speed로 car1에 입력된다
car1.color와 같이 참조하고 있는 type의 멤버필드에 초기값이 없더라도 정보를 저장하고 활용할 수 있다.
car1 = Car('tom', 10) # 생성자 호출 후 객체 생성
print(car1.handle, car1.name, car1.speed)
car1.color = '보라'
print('car21 color : %s' %car1.color)
0 tom 10
car21 color : 보라
서로 다른 객체 변수가 같은 type을 참조한다고 해서 이후에 생성한 필드 등의 데이터를 공유하지는 않는다.
예시에서는 car1에서 만든 color 필드를 car2에서 사용할 수 없다.
car2 = Car('james', 20)
print(car2.handle, car2.name, car2.speed)
#print('car2 color : %s' %car2.color) # 'Car' object has no attribute 'color'
0 james 20
모두 Car type을 객체에 참조하는 것은 동일하지만 id 값이 다르다.
print('주소 : ', id(Car), id(car1), id(car2))
주소 : 2652749020752 2652748507216 2652748560176
class - method
함수가 클래스 밖에 있으면 function, 클래스 안에 있으면 method라고 한다.
기존의 Car class의 showData 메소드를 약간 수정하였다.
class Car:
handle = 0 # Car type의 객체에 참조 가능 멤버 필드
speed = 0
def __init__(self, name, speed):
self.name = name
self.speed = speed
def showData(self): # Car type의 객체에서 참조 가능 멤버 메소드
km = '킬로미터'
msg = '속도:' + str(self.speed) + km + ', 핸들은' +str(self.handle)
return msg
객체변수는 기존 type을 참조해서 메소드를 실행한다.
예시에서 car1, car2가 Car type이기 때문에 미리 만들어둔 Car의 메소드 showData를 참조해 사용된다.
메소드를 호출하는 형식인 Bound method call, UnBound method call은 형식만 다르고 결과는 같다
print('method')
print(car1.showData())
print(car2.showData()) # Bound method call
print(Car.showData(car2)) # UnBound method call
method
속도:10킬로미터, 핸들은0
속도:20킬로미터, 핸들은0
속도:20킬로미터, 핸들은0
객체변수와 class의 데이터를 변경하는 것이 가능하다
car2.speed = 100
Car.handle = 1
car1.handle = 2
print('car2 : ', car2.showData())
print('car1 : ', car1.showData())
car2 : 속도:100킬로미터, 핸들은1
car1 : 속도:10킬로미터, 핸들은2
'python' 카테고리의 다른 글
class - 다른 모듈에서 import해서 사용하기 (0) | 2022.10.07 |
---|---|
class - 참조 및 콜 위치 (0) | 2022.10.07 |
class - 개요 (0) | 2022.10.07 |
module - opencv (0) | 2022.10.06 |
module - 라이브러리 (0) | 2022.10.06 |