본문 바로가기
Python/Web Scraping

[Python] #3.4 Methods part Two (#코딩공부)

by 함께 공부해요 2020. 3. 1.

https://youtu.be/UR4sPOR1oB8


<복습>

https://wook-2124.tistory.com/50

 

[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

 

<준비물>

https://repl.it/

 

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

 

<코드기록>

# dir은 class안에 있는  모든 것들(properties)을 list로 보여줌
class Car():
  wheels = 4
  doors = 4
  windows = 4
  seats = 4

print(dir(Car))


# 안에 있는 '__str__'은 class안에 이미 내재되어 있는 method(function)임
# 즉 어떤 argument가 와도 str(문자열)로 출력하고자 함을 내포한 것임
# 여기서 class 안에 있는 method 중 하나인 __str__() 을 override(재정의)하고 return 값을 해주면 내가 치는 값이 출력됨
# __str__() 에서 ()는 self를 지칭함
# python이 자동으로 porche.__str__()을 호출해서 porche를 print해도 내가 return한 값이 나오게 됨
class Car():
  wheels = 4
  doors = 4
  windows = 4
  seats = 4

  def __str__(self):
    return "I'm changing 'str' myself."

porche = Car()
print(porche)


# __init__이란 - class를 만들었을 때 바로 만들어지는 method
class Car():

  def __init__(self, *args, **kwargs):
    self.wheels = 4
    self.doors = 4
    self.windows = 4
    self.seats = 4

  def __str__(self):
    return f"Car with {self.wheels} wheels"


porche = Car()
print(porche)


# kwargs.get(k, d) - 
# k는 key(내가 원하는 것), d는 default(값)으로 내가 원하는 값이 없을 때 나타낼 값
# positional argument가 아닌 keyword argument로 지정해서 사용할 것이기 때문에 args는 사실상 필요없음
class Car():

  def __init__(self, *args, **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()
# ()안에 아무것도 입력하지 않아서 default value뜸
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)

1. dir

print(Car)을 출력해보면 그저 class인 '__main__.Car' 라고 나온다.

 

dir(Car)을 출력해보자. dir은 class안에 있는 모든 것들(properties, method), 즉 class의 내제된 기능들을 list로 보여준다.

 

class 안에 내재되어 있는 method(function)'__str__'은 어떤 argument(인자)가 와도 str(문자열)로 출력하고자 함을 내포한 것이다. 이것을 예제로 좀 더 이해해보자.


2. __str__

이렇게 print(porche)를 출력하면 __main__.Car의 object, 즉 instance인 산출물이라고 떠야한다.

 

그러나 내가 class 안에 있는 method 중 하나인 '__str__'를 class에 def로 override(재정의)하고 return 해주면, return 해준 값이 나온다. __str__() 에서 ()는 button은 self를 지칭한다.

 

**실제로는 python이 자동으로 porche.__str__()을 호출해서 porche를 출력해도 porche = Car()이 되기 때문에, return한 값이 나오게 되는 것이다.


3. override(재정의)

class 안에 있는 method(__str__)을 override(재정의)해주는 것은 그냥 class에 내제해서 def로 다시 정의해주기만 하면된다. 여기서는 __str__()에서 ()안에 있는 self 자체가 argument(인자)가 되서 porche를 print할 때마다 return 값인 문장이 출력되는 것이다.

 

저번시간에 했던 내용이지만, instance(산출물)은 class(설계도)의 method(function 함수, 기능)을 호출할 때 자동으로 첫번째 argument로 지정된다. 이것은 python에만 있는 규칙이다.


4. __init__

'__init__' 역시 class를 만들었을 때, 저절로 class에 내장되는 수많은 method 중 하나이다. 이것 역시 '__str__'처럼 재정의(override)할 수 있다.

 

keyword arguments를 무제한으로 지정하는 *kwargs를 이용해서, 원하는 값을 뽑아낼 수 있도록 method를 재정의했다.

 

kwargs.get(k, d)에서 k는 key(원하는 인자), d는 default(기본값)으로 default는 원하는 값이 없을 때 자동으로 나타낼 값이다.

 

원하는 key를 color로 지정하고, 그 key(color)가 나타나지 않을 때에는 black이라는 기본값이 나타날 것이다.

 

마찬가지로 price를 key로 두고 price가 제공되지 않는다면 나타낼 기본값을 $20로 정해뒀다.

 

print(porche.color, porche.pirce)를 출력하면 color = "Green", price = "$40" 처럼 key값을 입력해뒀기 때문에 default(기본값)이 아닌 key값이 출력됐다.

 

그리고 positional argument가 아니라 계속해서 color = "___", pirce = "___"처럼 keyword argument로 지정해서 사용할 것이기 때문에 args는 사실상 필요없다.


5. 정리

porche이외의 instance인 mini를 만들고 mini = Car()를 입력하면, () 안에 self, **kwargs로 각각 입력할 수 있다고 뜬다.

 

하지만 mini = Car()는 porche = Car(color = "Green", price = "$40")와 달리 ()안에 self, **kwargs가 입력되지 않아서 print(mini.color, mini.price)를 출력해도 kwargs.get에서 default value(기본값)이 나온다.

 

이렇게 keyword argument를 잘 활용하면, keyword argument를 지정하지 않아도 default value(기본값)이 나오기 때문에 유용하다.

 

class = 설계도(blueprint)

method = class안에 있는 function(def)

instance = class로 만든 산출물, 복제품

argument = ()안에 속하는 인자(a, b, ... , 뭐든지 가능!)

dir = 부품 하나하나 뜯어보기

override = class안에 있는 method 다시 정의하는 것


※ 신종 코로나 바이러스 조심하세요!!!!

댓글