본문 바로가기

개발이야기/Python

Python - 함수 (Function) / 메소드(Method)

Python에서는 함수를 만든다기보다 정의한다(define)고 하며 함수가 'def'로 시작한다.

Java 외의 다른 언어와 같이 함수의 처음과 끝을 중괄호{}로 표기하지 않고, 들여쓰기나 공백으로 표시한다.

 

# Java
function main() {
	System.out.println("HELLO")
}

# Python
def hello():
	print("HELLO")
print("BYE")

"""
위와 같이 작성했을 경우 "HELLO"는 함수내에 있지만
"BYE"는 함수 밖에 있기 때문에 hello()를 호출했을 때 작동하지 않음
"""

# Python 옳은 코드
def hello():
	print("HELLO")
	print("BYE")

 

또 하나의 특이점은 함수에 인자를 넘길 때 타입을 명시하지 않는다.

 

def say_hello(name) :
  print("hello ", name)

say_hello("Chris") # Hello Chris

def say_hello(name) :
  print("hello ", name)

say_hello(True) # "Hello True"

def greeting(name, age) :
	return f"Hello, my name is {name} and I'm {age} years old"
    #문장 앞에 f(format)를 사용하여 자바스크립트의 백틱(backtick)과 비슷하게 사용할 수 있다.
    
hello = greeting("Chris", "12")
print(hello)

 

다음과 같은 코드가 있다고 하자.

 

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

def minus(c, d):
  print(c - d)
  
plus(3, 4) # 7
plus(b=3, a=5) # 8 (이런 식으로 인자의 순서가 바뀌더라도 작동한다.)
minus(4) # error

 

minus()를 호출할 때 인자가 2개가 필요하기 때문에 하나만 입력할 경우 에러가 발생한다.

이를 막기 위해 minus의 파라미터에 기본값을 설정해준다.

 

def say_hello(name="anonymous"):
  print("Hello:: ", name)
    
def minus(c, d=1):
  print(c - d)
  
say_hello() # "hello anonymous"
minus(3) # 2

조건문(if ~ else) / 비교문

큰 차이가 없기 때문에 추가적인 설명은 하지 않았다.

 

def plus(a,b):
 # Python에서는 ==는 값의 동일함을, is는 객체의 동일함을 비교한다.
  if type(b) is int or type(b) is float:
      return a+b
  else:
      return None
        
print(plus(12, 34)) # 46
print(plus(12, "34")) # None

Method(메소드)

메소드를 사용할 경우를 살펴보자.

간단하게 얘기하자면 함수는 객체와 독립적으로 동작하는 반면, 메소드는 객체에 종속된다. 

함수와 메소드의 차이점👇
https://merry-mj.tistory.com/18

 

 

class Car():
  wheels = 4
  doors = 4
  
  def start():
    print("I started")

porche = Car()
porche.start()

 

위의 코드를 실행시키면 아래와 같은 오류가 발생한다.

Traceback (most recent call last): File "main.py", line 27, in <module> porche.start() TypeError: start() takes 0 positional arguments but 1 was given

 

나는 분명 start에 인자를 넘기지 않았는데 무슨 일일까!?이는 파이썬이 준 것이다!

 

파이썬은 모든 함수를 하나의 인자(argument)와 함께 사용한다. 무슨 말이냐면, 메소드의 첫 번째 인자는 메소드를 호출하는 instance 그 자신이라는 것이다.

 

class Car():
  wheels = 4
  doors = 4
  
  def start(self):
  	print(self)
    print("I started")

porche = Car()
porche.start()

 

따라서 해당 instance를 출력하면 아래와 같고, 이는 porche.start(porche)와 같은 의미이다.

<__main__.Car object at 0x7ffa1813b610>

클래스의 확장(Extension)

클래스의 확장이란 부모 클래스를 상속받는 개념이다. 따라서 부모 클래스에 구현되어있는 메소드를 따로 재구현할 필요없이 그대로 사용가능하다. (Java에서는 class A extends B 형태로 사용한다.)

 

파이썬은 자바보다 훨씬 간편하게 확장이 가능하다. 위에 작성해둔 Car 클래스를 상속받는 Convertible 클래스를 작성해보면 아래와 같다.

 

class Car():
  wheels = 4
  doors = 4
  
  def start(self):
    print(self)
    print("I started")

porche = Car()
porche.color = "Redddd"
porche.start()

class Convertible(Car):

  def take_off(self):
    return "taking off"
  
ferrari = Convertible()
print(ferrari.wheels) # 4
takeoff = ferrari.take_off()
print(takeoff) # taking off

 

Convertible 클래스에 wheels에 대한 값이 설정되어 있지 않지만, Car 클래스를 상속받아 wheels에서 4가 출력되었다.

방법은 새로 만든 클래스명 옆 괄호 안에 상속받고자 하는 클래스명만 입력해주면 끝! 매우 간단하다.

 

'개발이야기 > Python' 카테고리의 다른 글

Python - StackOverflow Scrapper 만들기  (0) 2021.06.07
Python - Indeed Scrapper 만들기  (0) 2021.06.03
Python - 변수 타입(Variable Type)  (0) 2021.06.02