[Python] #3.5 Extending Classes / #3.6 Whats Next (#코딩공부)
<복습>
https://wook-2124.tistory.com/51
[Python] #3.3 Methods part One (#코딩공부)
https://youtu.be/dQK55j3D6cQ <복습> https://wook-2124.tistory.com/48 [Python] #3.2 Intro to Object Oriented Programming (#코딩공부) https://youtu.be/OiaXhERY3Kw <복습> https://wook-2124.tistory.com/..
wook-2124.tistory.com
<준비물>
Online IDE, Editor, and Compiler - Fast, Powerful, Free
Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin (beta), QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeS
repl.it
<코드기록>
# inherit(상속), extend(확장)하기
# class Convertible()에서 ()에 부모 class의 이름을 적으면 됨
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 Convertible(Car):
def take_off(self):
return "taking off"
porche = Convertible(color = "Green", price = "$40")
porche.take_off()
porche.wheels
# class Cars_son_of_son은 자기의 할아버지 격인 Car의 모든 method를 갖게됨
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 Convertible(Car):
def take_off(self):
return "taking off"
class Cars_son_of_son(Convertible):
pass
porche = Convertible(color = "Green", price = "$40")
porche.take_off()
porche.wheels
# override(재정의)한 것 다시 override하기
# 그러나 이렇게 override하게 되면 말그대로 color같이 원래 갖고있는 속성도 사라지게 됨
# 그저 __init__에 항목을 하나 더 추가하고 싶었을 뿐인데도
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 Convertible(Car):
def __init__(self, **kwargs):
self.time = kwargs.get("time", 10)
def take_off(self):
return "taking off"
def __str__(self):
return f"Car with no roof"
class Cars_son_of_son(Convertible):
pass
porche = Convertible(color = "Green", price = "$40")
print(porche.color)
# super()를 통해서 부모클래스에 접근한 뒤 .__init__ method를 호출함
# super = father, upper class
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 Convertible(Car):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.time = kwargs.get("time", 10)
def take_off(self):
return "taking off"
def __str__(self):
return f"Car with no roof"
class Cars_son_of_son(Convertible):
pass
porche = Convertible(color = "Green", price = "$40")
print(porche.color)
1. inherit(상속) · extend(확장)
class Convertible()에서 ()에 부모 class인 Car를 적으면 Convertible은 Car의 모든 method를 물려받는다.
class Cars_son_of_son가 Convertible을 inherit해도, 자기의 할아버지 격인 Car의 모든 method를 갖게된다.
2. override(재정의)한 것 다시 override하기
class Car안에 있는 __str__(self)를 class Convertible에서 override해서 "Car with no roof"가 출력됐다.
그러나 override는 말 그대로 다시 정의하는 것이기 때문에, 아들 class인 Convertible에서 __init__에 항목을 하나 더 추가하려한 것이지만, 아빠 class인 Car __init__에 있는 wheels, doors, windows, seats, color, price는 모두 없어지고 time만 생기게 된다.
때문에 override(def)는 상위 class에 있는 것을 말그대로 뒤바꿀 때 써야한다.
3. super().something
하위 class인 Convertible에서 __init__을 더 추가하고 싶을 때는 super().으로 부모 class에 접근한 뒤
class Car에 지정해둔 __init__(self, **kwargs)를 호출하면 된다.
이렇게 하면 Car() 안에 있는 def __init__(self, **kwargs) 전체가 호출이되고, self.time도 추가할 수 있다.
그러나 전 사진처럼 self까지 호출하게 되면, 2개의 argument가 주어졌다면서 오류가 뜬다.
때문에 super().__init__(**kwargs)처럼 self를 지워 1개의 argument(**kwargs)만 주면, Convertible은 Car의 속성인 color도 갖게되고 self.time도 추가해서 time도 갖게 된다.
마지막으로 이렇게 Method와 Extend, Inherit에 대해서 알아본 것은 Django에 대해 알기 위함이다.
Django는 쉽게 생각해서 좋은 Class들의 모임이다. 종종 extend 할 때가 있고, 안에 있는 method를 따로 사용할 수도 있다.
또 super()를 사용해서 upper class의 method를 호출할 수도 있다. (super class는 하위 class가 extend한 상위 class)
그리고 필요한 argument 값이 없으면 default(기본값)이 출력되기 때문에, argument도 keyword로 잘 정할 필요가 있다.
https://github.com/wook2124/Python_Course
wook2124/Python_Course
Nomad Coders's Python Course. Contribute to wook2124/Python_Course development by creating an account on GitHub.
github.com
Python Course 끝, JavaScript Course 시작!
※ 신종 코로나 바이러스 조심하세요!!!!