"Django makes it easier to build better web apps more quickly and with less code"
원래 함수 인자보다 더 많은 인자를 전달하면 오류가 발생함
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
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
class
안에 있는 functionclass 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']
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
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
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
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으로 웹 스크래퍼 만들기