Tiny Finger Point Hand With Heart
본문 바로가기
Python

더 이상 미룰 수 없다. 나의 취직과 파이썬메서드/함수공부(메서드와 함수의 차이)

by yoondii 2023. 1. 16.
728x90
반응형

알고리즘을 풀면서 파이썬의 내장함수와 메서드를 제대로 활용하지 못하고 있음을 느꼈고,

저번 프로젝트했을 때에도 함수 사용법을 제대로 몰라 활용하지 못했던 경험이 있다.

당시 나의 심정

그래서 이번에 정확이 알아가고자 한다. 너무 늦었지만...당장시작합니다


먼저 함수와 메서드의 차이를 알아보자.

1. 함수(function)

함수 기본구조

함수명()

def function_name(arg1,arg2,...):
    ...
    # function body
    ...
    

def Subtract(a,b):
    return a-b

print(Subtract(10,12))
print(Subtract(15,6))

결과 = -2
결과 = 9
  • 함수 이름을 통해 함수를 사용할 수 있다.
  • 함수 예) print(), type(), str(), int(), bool(),
  • 함수의 값을 변수에 대입할 수 있다.
    👉🏻 output = function_name(input)
  • Function is block of code that is also called by its name. (independent)
    함수는 코드 블록이며, 이름으로도 불린다(독립)
  1. The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.
    함수의 매개변수가 다르거나 하나도 없을 수 있다. 전달도니 데이터(매개변수)가 있으면, 매개변수들은 명시적으로 전달된다.
  2. It may or may not return any data.
    데이터가 반환되거나 반환되지 않을 수 있다.
  3. Function does not deal with Class and its instance concept.
    함수는 클래스 및 클래스 인스턴스 개념을 다루지 않는다.



2. 메서드(method)

메소드 기본구조

object.method_name()

class class_name:
    def method_name(*args,**kwargs):
        ...
        # method body
        ...

class ABC:
    def method_abd(self):
        print("I am in method_abc of ABC class.")
        
class_ref = ABC()
class_ref.method_abd()

결과 = I am in method_abc of ABC class.
  • object(객체)와 연관되어 사용된다. → 사용하고자 하는 대상이 . 으로 연결되어있어야함
  • str,float,list와 같은 자료형은 모두 객체이므로 이러한 자료형과 연관되어 사용되는 것은 메소드로 볼 수 있다.
  • 메소드 예) .split() , .append() 등
  • Method is called by its name, but it is associated to an object (dependent).
    메서드가 이름으로 호출되지만 객체와 연결되어 있다.(종속)
  • A method is implicitly passed the object on which it is invoked.
    메서드는 메서드가 호출되는 개체를 암시적으로 전달한다.
  • It may or may not return any data.
    데이터가 반환되거나 반환되지 않을 수 있다.
  • A method can operate on the data (instance variables) that is contained by the corresponding class.
    메서드는 해당 클래스에 포함된 데이터(인스턴스 변수)에서 작동할 수 있다.



3. 함수와 메소드의 차이점

  1. Simply, function and method both look similar as they perform in almost similar way, but the key difference is the concept of ‘Class and its Object‘. 
    간단히 말해서, function과 method는 거의 비슷한 방식으로 수행될 때 비슷하게 보이지만, 핵심적인 차이점은 '클래스와 그것의 객체'의 개념이다.
  2. Functions can be called only by its name, as it is defined independently. But methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class. 함수는 독립적으로 정의되므로 이름으로만 호출할 수 있습니다. 그러나 메소드는 이름만으로 호출될 수 없다. 클래스가 정의된 클래스의 참조로 클래스를 호출해야 한다. 즉 메소드는 클래스 내에서 정의되므로 클래스에 종속된다.

 

 

 

 

출처-

https://velog.io/@yejin20

https://sikaleo.tistory.com/

https://wikidocs.net/

 

728x90
반응형

댓글