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 to RubyAdvent Calendar 2021

Day 3

[py2rb] 関数の属性

Last updated at Posted at 2022-02-01

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

関数の属性 (Python)

def make_func(x):
    def func1():
        return '1'
    def func2():
        return '2'
    func1.__doc__ = x
    func1.other = func2
    return func1

my_func = make_func("func1")
print(my_func())
print(my_func.__doc__)
print(my_func.other())

# output
1
func1
2 

関数の属性という説明が正しいか自信はないのですが、特殊属性の代表である__doc__ドキュメンテーション文字列の他、自作関数を属性として追加し、呼び出すことができます。

どうする (Ruby)

make_func = lambda do |x = nil, *args, **kwargs|
  def func1()
    return '1'
  end
  def func2()
    return '2'
  end
  if x.nil?
    func1
  elsif x == 'other' || x == :other
    func2
  end
end

my_func = make_func
puts my_func.call()
puts my_func.call('other')

# output
1
2

__doc__はPythonの文化なので使用しないと思いますが、必要があればdef __doc__の追加で対応できそうです。

メモ

  • Python の 関数の属性 を学習した
  • 百里を行く者は九十里を半ばとす
0
0
2

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?