파이썬은 객체지향 언어이다.
그리고 객체지향을 이루는 특성들이 바로
Class, Method, Instance 등의 요소들인데 각 각 무엇인지
정리를 해보자!
파이썬
class
- 아이언맨 설계도(blueprint)
method
- class 내에 있는 함수(function)
instance
- 아이언맨 설계도의 결과물
파이썬은 Method를 호출할 때, 그 method의 instance를 첫 번째 argument로 사용한다.
(self)를 엄청나게 봐왔던 이유가 이거 였구만....
Class 예제 1.
class Car():
wheels = 4
doors = 4
windows = 4
seats = 4
def start(self) :
print(self.doors)
print(“I started”)
porche = Car()
porche.color = “Red Sexy Red”
porche.start(porche)
실행결과
4
I started
Class 예제 2.
class Car():
def __init__(self, **kwargs):
self.wheels = 4
self.doors = 4
self.windows = 4
self.seats = 4
self.color = kwargs.get("color", "black")
self.price = kwargs.get("price", "$20")
def __str__(self):
return f"Car with {self.wheels} wheels"
porche = Car(color="green", price = "$40")
print(porche.color, porche.price)
mini =Car()
print(mini.color, mini.price)
실행결과
green $40
black $20
Class 예제 3.
class Car():
def __init__(self, **kwargs):
self.wheels = 4
self.doors = 4
self.windows = 4
self.seats = 4
self.color = kwargs.get("color", "black")
self.price = kwargs.get("price", "$20")
def __str__(self):
return f"Car with {self.wheels} wheels"
# class의 확장(extension)
class Convertible(Car):
def __init__(self, **kwargs):
# method의 확장(extension)
# super = 함수가 부모 class를 호출하는 함수이다.
super().__init__(**kwargs)
self.times = kwargs.get("time", 10)
def take_off(self):
return "taking off!"
def __str__(self):
return f"Car with no roof"
porche = Convertible(color="green", price="$40")
porche.take_off()
porche.wheels
print(porche.color)
print(porche)
print(porche.times)
print(porche.wheels)
실행결과
green
Car with no roof
10
4
결론 - django는 좋은 class 들의 모임인 것이다.
'Tech Blog > Python' 카테고리의 다른 글
Python - 데이터 타입 정리(숫자,텍스트,리스트,튜플,딕셔너리 등) (0) | 2021.06.23 |
---|---|
파이썬 - 문자열 제거 및 추출과 revsqueeze, hex to int 실습 (0) | 2021.06.22 |
파이썬 Tensorflow 데이터 사이언스에 빠져들다!! (0) | 2021.05.11 |
데이터 사이언스 Tool, Orange3 소개 (0) | 2021.05.10 |
(셀레니엄)나이키 자동응모 웹 자동화 도전했으나... (0) | 2021.05.10 |