0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

移植やってます。

デコレーター (Python)

# ----------
# Name: hoge
# Args: (15, 37)
# Kwargs: {'m': 'ほげ', 'n': 'ぴよ'}
# ----------
# hoge: 15-37/ほげ-ぴよ

独習Pythonのデコレーターを利用しない例を写経してみます。

どうする? (Ruby)

def log_func(func)
  def inner(*args, **kwargs)
    puts "----------"
    puts "Name: #{__method__}"
    puts "Args: #{args}" if args.nil?.!
    puts "Kwargs: #{kwargs}" if kwargs.nil?.!
    puts "----------"
    func.call(args, kwargs)
  end
  inner
end

def hoge(x, y, m: 'bar', n: 'piyo')
  puts "hoge: #{x}-#{y}/#{m}-#{n}"
end

log_hoge = log_func(method(:hoge))
log_hoge(15, 37, m: 'ほげ', n: 'ぴよ')

# ----------
# Name: inner
# Args: []
# Kwargs: {}
# ----------
#in `inner': undefined local variable or method `func' for main:Object (NameError)

本の内容に近いコード。
エラーが出ています。

def log_func(func, *args, **kwargs)
  def inner(func, *args, **kwargs)
    puts "----------"
    puts "Name: #{__method__}"
    puts "Args: #{args}" if args.nil?.!
    puts "Kwargs: #{kwargs}" if kwargs.nil?.!
    puts "----------"
    func.call(args, kwargs)
  end
  inner(func, args, kwargs)
end

def hoge(x, y, m: 'bar', n: 'piyo')
  puts "hoge: #{x}-#{y}/#{m}-#{n}"
end

log_hoge = log_func(method(:hoge), 15, 37, m: 'ほげ', n: 'ぴよ')

# ----------
# Name: inner
# Args: [[15, 37]]
# Kwargs: {:m=>"ほげ", :n=>"ぴよ"}
# ----------
# hoge: [[15, 37]]-{:m=>"ほげ", :n=>"ぴよ"}/bar-piyo

引数の受け渡しが不味そう。
hogeの出力が正しくない。

def log_func(func, *args, **kwargs)
  inner = proc {
    puts "----------"
    puts "Name: #{__method__}"
    puts "Args: #{args}" if args.nil?.!
    puts "Kwargs: #{kwargs}" if kwargs.nil?.!
    puts "----------"
    func.call(*args, **kwargs)
  }
  inner.call
end

def hoge(x, y, m: 'bar', n: 'piyo')
  puts "hoge: #{x}-#{y}/#{m}-#{n}"
end

log_hoge = log_func(method(:hoge), 15, 37, m: 'ほげ', n: 'ぴよ')

# ----------
# Name: log_func
# Args: [15, 37]
# Kwargs: {:m=>"ほげ", :n=>"ぴよ"}
# ----------
# hoge: 15-37/ほげ-ぴよ

procでやってみた。
出力はよさそう。
メソッド名はもちろん異なっています。

メモ

  • Python の デコレーター を学習した
  • 道のりは遠そう
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?