Tech Blog/Python
Python - Class, Method, Instance 정리 글
EXPRESSIONS HAVE POWER
2021. 6. 20. 16:31
파이썬은 객체지향 언어이다.
그리고 객체지향을 이루는 특성들이 바로
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 들의 모임인 것이다.