Basic concept of Django

shin·2022년 3월 24일
0

Python Web

목록 보기
5/6
post-thumbnail

1. Django : Web Framework

  • 관련 자료 : Django Project
  • "Django makes it easier to build better web apps more quickly and with less code"
  • 파이썬만 사용해서 FrontEnd에 BackEnd API를 만들 수 있음
  • instagram과 Pinterest는 Django로 만들어짐

2. *args & **kwargs

원래 함수 인자보다 더 많은 인자를 전달하면 오류가 발생함

def plus(a, b):
  return a + b

plus(1, 1, 1, 1) # error

*args를 사용하면 positional arguments가 엄청 많을 것이라는 것을 파이썬이 알 수 있고, 해당 인자들을 Tuple 형태로 받을 수 있음

def plus(a, b, *args):
  print(args)
  return a + b

plus(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

같은 함수에 keyword arguments를 전달하면 오류가 발생함

def plus(a, b, *args):
  print(args)
  return a + b

plus(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    hello=True, hi=True, bye=True)
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    plus(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
TypeError: plus() got an unexpected keyword argument 'hello'

**kwargs를 사용하면 keyword arguments도 받을 수 있음
이때 keyword arguments는 dictionary 형태로 반환됨

def plus(a, b, *args, **kwargs):
  print(args)
  print(kwargs)
  return a + b

plus(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    hello=True, hi=True, bye=True)
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
{'hello': True, 'hi': True, 'bye': True}

*args를 이용해서 전달받은 인자들을 전부 더하는 함수를 만들 수 있음

def plus(*args):
  result = 0
  for number in args:
    result += number
  print(result)

plus(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
16

3. Object Oriented Programming

1) Class & instance

class Car(): # blueprint
  wheels = 4
  doors = 4
  windows = 4
  seats = 4

porche = Car() # instance of Car class
porche.color = "Red" # 확장

ferrari = Car()
ferrari.color = "Yellow"

mini = Car()
mini.color = "White"

print(porche.color)
print(ferrari.color)
print(mini.color)
Red
Yellow
White

2) Method

  • method : class 안에 있는 function
class Car():
  wheels = 4
  doors = 4
  windows = 4
  seats = 4
  
  def start(): # method
    print("I started")

porche = Car() 
porche.start()
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    porche.start()
TypeError: start() takes 0 positional arguments but 1 was given
  • 오류가 발생하는 이유
    • Python calls all methods with one argument
    • one argument : method를 호출하는 instance 자신
class Car():
  wheels = 4
  doors = 4
  windows = 4
  seats = 4

  def start(self):
    print(self.color) 
    print("I started")

porche = Car()
porche.color = "Red"
porche.start() // == porche.start(porche)
Red
I started
  • dir() : class 안에 있는 모든 properties를 리스트로 보여줌
class Car():
  wheels = 4
  doors = 4
  windows = 4
  seats = 4

print(dir(Car))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'doors', 'seats', 'wheels', 'windows']

3) override

  • override : class에 이미 존재하는 method를 다시 만듦
class Car():

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

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

porche = Car()
print(porche) # == print(porche.__str__())
Car with 4 wheels
  • 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")

porche = Car(color="green", price="$40")
print(porche.color, porche.price)

mini = Car()
print(mini.color, mini.price) # default value
green $40
black $20

4. Extending Classes

1) inheritance (상속) : extended Parent class

  • 자식이 부모가 가진 것을 모두 사용할 수 있게 됨
  • 부모의 method를 override해서 새로운 기능으로 사용할 수 있음
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"

# inheritance - extended Car class
class Convertible(Car):

  def take_off(self):
    return "taking off"

  # override
  def __str__(self):
    return f"Car with no roof "

porche = Convertible(color="green", price="$40")
print(porche.take_off())
print(porche.wheels)
print(porche)
taking off
4
Car with no roof 

2) method extend

  • child class에서 __init__ method를 override
  • __init__ 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")

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

# inheritance - extended Car class
class Convertible(Car):

  def __init__(self, **kwargs):
    self.time = kwargs.get("time", 10)

  def take_off(self):
    return "taking off"

  # override
  def __str__(self):
    return f"Car with no roof "

porche = Convertible(color="green", price="$40")
print(porche.color)
Traceback (most recent call last):
  File "main.py", line 29, in <module>
    print(porche.color)
AttributeError: 'Convertible' object has no attribute 'color'
  • __init__ method를 완전히 대체하는 것이 아닌 확장시키기 위해 super() 사용
  • super() : 부모 클래스를 호출하는 함수
  • super().method() : 부모 클래스의 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")

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

# inheritance - extended Car class
class Convertible(Car):

  def __init__(self, **kwargs):
    # 부모 클래스의 __init__ method 호출
    # 만약 super().__init__()이라면 default로 설정된 black이 출력됨
    super().__init__(**kwargs) 
    self.time = kwargs.get("time", 10)

  def take_off(self):
    return "taking off"

  # override
  def __str__(self):
    return f"Car with no roof "

porche = Convertible(color="green", price="$40")
print(porche.color)
green

출처 : Python으로 웹 스크래퍼 만들기

profile
Backend development

0개의 댓글