#02 Arguments and Object-oriented programming

Elliott·2021년 5월 9일
0

노트가 다 지워졌다...... 복구할 수 있는대로 써보겠습니다.

Note

There are two important concepts of Django that I need to know to learn it: arguments and keyword arguments, and object-oriented programming such as class, inheritance(상속), method

# Arguments and Keyword arguments

  • print와 같이 무한한 인자를 내가 만든 function에 넣고 싶다면, 두 가지 방법이 있다.

1) *args

  • args는 arguments의 줄임으로(positional arguments), 아래와 같이 작성해주면 plus에 넣은 인자 중 맨 앞 1, 2를 제외한 나머지가 *args에 할당되어 프린트된다.

그러나 아래와 같이 keyword arguments를 넣으려 하면 에러가 나는데, it means the print function is not prepared to deal with these things. 이때는 두 번째 방법을 써야한다.

2) **kwargs

  • It is used when I want to deal with infinite amount of keyward arguments.

  • *args는 tuple type으로, **kwargs는 dictionary로 나옴을 확인할 수 있다.

ex. 이를 이용해 여러 수에 대한 calculator를 만들 수도 있다.

# Object-oriented programming

: It is a way to organize my code and many languages are also object-oriented such as Java, Dart, and Swift. So this concept applies to all those languages.

1) Class

: Class is basically a blueprint. I would want to have a blueprint of something that I want to make. And then I can have many instances of the blueprint, an alive copy and a product of that blueprint and I can make it as many as I want.
아래와 같이 내가 앞으로 만들 모든 것들에 대해 base를 만드는 것.
아래의 코드에서 porche와 ferrari는 Car의 instances라고 할 수 있다.

  • porche = Car() >>> 함수를 호출하는 것처럼 class 이름 뒤에 괄호를 붙여 take the blueprint and instance를 만든 것. This is called instantiation.

2) Method

: A method is a function inside a class. Indentation matters!

  • 좌측과 같이 코드를 입력했던. start() takes 0 positional argument but 1 was given이란 에러 메시지가 뜬다. 첫번째 문장은 사실이지만 두 번째 문장에서 말하는 주어진 1 argument는 python이 준 것. Python calls all methods with one argument. The first argument of a method(a function inside a class) is "self"(the instance itself that is calling the method). >>> 따라서 method를 만들 때는 최소 하나의 인자가 들어갈 자리를 만들어줘야 한다. 보통 self를 많이 쓰나 다른 이름이어도 상관없다.

  • dir lists everything inside of a class. print(dir(Car))하면 Car의 properties들을 볼 수 있다.

  • Methods inside of a class can be overridden(재정의).

  • init
    init in Python 설명
    https://www.geeksforgeeks.org/__init__-in-python/
    : The init method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

  • 아래의 코드에서 self.color = kwargs.get("color", "black") 그리고 self.price = kwargs.get("price", "$20")으로 지정해줌으로써 Car의 instance인 porche = Car(color="green", price="$40")이 만들어졌을 때 딕셔너리에서 "color"와 "price" 키에 할당된 value들이 추출되어 poche.color = "green", porche.price = "$40"이 된다. kwargs.get(k, d)에서 뒤에 들어가는 인자는 default 값으로 mini의 color와 price처럼 지정된 값이 따로 없을 때 출력된다.

3) Inheritance(상속) - Extending Classes

: Sometimes what I'd like to do could be to make a car that is different from Car class but is the same. For example, I might want to make a car that is convertible so that we can open the roof. We can make a method in the Car class already made, but in this case, the problem is that cars that don't need the function will also be affected by the method. So it doesn't fit the Car class. What can we do?

1) Copy and paste the Car class, and change the name of the copied class adding specific methods. >>> This is wrong! because we never want to repeat ourselves.

2) What we are gonna do is Interitance/Extension. Then we can get all the properties of the Car class for free. We don't have to do copy and paste again.

  • 아래와 같이 써주면 Convertible이라는 새 class 안에 Car의 속성들도 모두 포함된다. Now, I have extended the Car class. >>> The Car class is inside of Convertible.

  • I can keep extending if I want like below.

# Important #

: 위의 코드에서 Convertible의 str method를 수정하고 싶다하면 문제가 없다. 그냥 Convertible class에 새 str method를 써주면 overwrite 된다. 하지만 init method에 있는 모든 property들을 그대로 두고 단 하나의 property만 추가 시키고 싶다면? init method 전체를 복붙하지 않는 이상 overwrite를 할 경우 Car class에 init method에 있던 모든 내용이 날아가는 문제가 생긴다.

  • 이럴 때 사용하는 걸 super라고 부른다. super is a function that basically calls the upper(parents) class. 아래와 같이 적어주면, super()로 upper class인 Car을 부르고, Car의 init method를 호출한 것.

    super is the class that I extended from.

0개의 댓글

관련 채용 정보