Python & Ruby

모듈

모듈이란?

내장모듈

Python 

import math
print(math.ceil(2.9))
print(math.floor(2.9))
print(math.sqrt(16))
3
2
4.0

ideone.com

Ruby

puts(Math.sqrt(16))
4.0

ideone.com

모듈에 없을 때

Python

def egoing_a():
    return 'a'
#엄청 많은 코드
def k8805_a():
    return 'B'
#엄청 많은 코드
print(egoing_a())

Ruby

def egoing_a()
  return 'a'
end
#엄청 많은 코드
def k8805_a()
  return 'B'
end
#엄청 많은 코드
puts(egoing_a())

실행결과

a

Python | Ruby 

모듈의 도입 - 파이썬

Python

egoing.py

def a():
    return 'a'
def b():
    return 'b'
def c():
    return 'c'

k8805.py

def a():
    return 'B'

 3.py

from egoing import a as z
import k8805 as k
print(z())
print(k.a())
a
B

모듈의 도입 - 루비

Ruby 

egoing.rb

module Egoing
  module_function()
  def a()
    return 'a'
  end
end

k8805.rb

module K8805
  module_function()
  def a()
    return 'B'
  end
end

3.rb

require_relative 'Egoing'
require_relative 'K8805'
puts(Egoing.a())
puts(K8805.a())
a
B

모듈을 통한 중복의 제거 & 재활용성의 증대

Python

egoing.py

def a():
    return 'a'
def b():
    return 'b'
def c():
    return 'c'

4_1.py

import egoing
print(egoing.a())
a

4_2.py

import egoing
print(egoing.a())
a

로그인 에플리케이션

Python 

auth.py

def login(_id):
    members = ['egoing', 'k8805', 'leezche']
    for member in members:
        if member == _id:
            return True
    return False

5.py

import auth
input_id = input("아이디를 입력해주세요.\n")
if auth.login(input_id):
    print('Hello, '+input_id)
else:
    print('Who are you?')

Ruby

auth.rb

module Auth
  module_function()
  def login(_id)
    members = ['egoing', 'k8805', 'leezche']
    for member in members do
        if member == _id
            return true
        end
    end
    return false
  end
end

5.rb

require_relative 'Auth'
puts("아이디를 입력해주세요")
input_id = gets.chomp()
if Auth.login(input_id)
  puts('Hello, '+input_id)
else
  puts('Who are you?')
end

댓글

댓글 본문
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기